Rules Hub
Code Ruleset
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Align I/O type assertions with return generics
Align validated values with the declared generic return contract; never use a return-type cast as a substitute for validating external data.
Bad example
| 1 | async function fetchApi<TOut, TIn = TOut>( |
| 2 | url: string, |
| 3 | transform?: (data: TIn) => TOut |
| 4 | ): Promise<TOut> { |
| 5 | const response = await fetch(url); |
| 6 | |
| 7 | // Bad: Casting to input type TIn causes errors when returning as TOut, |
| 8 | // often leading developers to use @ts-expect-error to silence it. |
| 9 | // @ts-expect-error |
| 10 | const data = (await response.json()) as TIn; |
| 11 |
|
| 12 | if (transform) return transform(data); |
| 13 | return data; // Error: TIn is not assignable to TOut |
| 14 | } |
Explanation (EN)
Asserting raw JSON to whichever generic satisfies the compiler does not establish a valid runtime shape.
Objašnjenje (HR)
Pretvaranje sirovog JSON-a u generički tip koji zadovoljava compiler ne dokazuje ispravan oblik tijekom izvođenja.
Good example
| 1 | async function read<T>(url: string, parse: (raw: unknown) => T): Promise<T> { |
| 2 | const response = await fetch(url); |
| 3 | if (!response.ok) throw new Error(`HTTP ${response.status}`); |
| 4 | const raw: unknown = await response.json(); |
| 5 | return parse(raw); |
| 6 | } |
Explanation (EN)
The parser validates the unknown payload and produces the promised return type.
Objašnjenje (HR)
Parser provjerava nepoznati sadržaj i proizvodi obećani povratni tip.
Notes (EN)
At a generic data boundary, validate unknown input before treating it as the declared return type; keep input and output types distinct when applying a transform.
Exceptions / Tradeoffs (EN)
Balance against validate-external-responses-not-blind-cast: align the cast with the return generic only for already-trusted/internally-validated data, not raw network input. A narrow assertion may document already-validated internal data, but it must not replace validation or claim arbitrary TOut compatibility.