Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Don't narrow a union return type just to avoid casts
If a function can genuinely return T or T[], keep the union (or use overloads); narrowing the signature to T to skip `as` casts hides runtime array cases from the type checker.
Bad example
| 1 | // runtime can return an object OR an array |
| 2 | function serialize<T>(dto: new () => T, data: unknown): T { |
| 3 | return plainToClass(dto, data); // actually returns T | T[] |
| 4 | } |
| 5 |
|
| 6 | // callers stop casting, but an array now masquerades as a single T |
| 7 | const one: User = serialize(User, payload); |
Explanation (EN)
The signature claims a single T while the implementation can still produce an array. Callers lose the type warning and can dereference array results as if they were objects.
Objašnjenje (HR)
Potpis tvrdi da vraca jedan T, dok implementacija i dalje moze proizvesti niz. Pozivatelji gube upozorenje tipova i mogu koristiti rezultat-niz kao da je objekt.
Good example
| 1 | // keep the honest union |
| 2 | function serialize<T>(dto: new () => T, data: unknown): T | T[] { |
| 3 | return plainToClass(dto, data); |
| 4 | } |
| 5 |
|
| 6 | // or be precise with overloads |
| 7 | function serializeOne<T>(dto: new () => T, data: object): T; |
| 8 | function serializeMany<T>(dto: new () => T, data: object[]): T[]; |
Explanation (EN)
Keeping the union (or splitting into overloaded/dedicated functions) keeps the type system honest so callers handle the array case explicitly.
Objašnjenje (HR)
Zadrzavanje unije (ili razdvajanje na preopterecene/namjenske funkcije) cuva sustav tipova postenim pa pozivatelji eksplicitno obraduju slucaj niza.
Exceptions / Tradeoffs (EN)
If the function provably returns only a single object for the given inputs, refactor the implementation to match the narrow type instead of just changing the annotation.
Iznimke / Tradeoffi (HR)
Ako funkcija dokazivo vraca samo jedan objekt za dane ulaze, prepravite implementaciju da odgovara uskom tipu umjesto da samo promijenite anotaciju.