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).
Type loosely-shaped upstream data as unknown and validate before use
When a field comes from an upstream type that's only loosely typed (e.g. `{ [key: string]: any }`), accept it as `unknown` in the function that reads it and runtime-check each value before use, instead of trusting the declared shape.
Bad example
| 1 | function storyFrom(title: string, url: string): FrontpageStory[] { |
| 2 | return [{ title: title.trim(), url }]; |
| 3 | } |
| 4 | // data: { id: string; [key: string]: any } upstream — title/url aren't guaranteed to be strings |
Explanation (EN)
The upstream item's `data` field is only loosely typed (`{ id: string; [key: string]: any }`) and the same array also holds placeholders/widgets with different shapes. Declaring `title`/`url` as `string` here just casts away the real uncertainty — `.trim()` can throw at runtime on a non-string value.
Objašnjenje (HR)
Polje `data` iz izvora tipizirano je labavo (`{ id: string; [key: string]: any }`), a isti niz sadrzi i placeholdere/widgete drugacijeg oblika. Deklariranje `title`/`url` kao `string` ovdje samo odbacuje stvarnu nesigurnost — `.trim()` moze baciti gresku u runtimeu na ne-string vrijednosti.
Good example
| 1 | function storyFrom(title: unknown, url: unknown): FrontpageStory[] { |
| 2 | if (typeof title !== 'string' || typeof url !== 'string') return []; |
| 3 | return [{ title: title.trim(), url }]; |
| 4 | } |
Explanation (EN)
Typing the inputs as `unknown` forces every caller path to prove the value is a string before using string methods on it, so malformed or unexpected upstream items are skipped instead of throwing.
Objašnjenje (HR)
Tipiziranje ulaza kao `unknown` prisiljava svaku putanju poziva da dokaze da je vrijednost string prije koristenja string metoda, tako da su neispravne ili neocekivane stavke iz izvora preskocene umjesto da bacaju gresku.
Notes (EN)
Add a short comment noting *why* the field is unknown (which upstream type it comes from) so future readers don't loosen it back to a concrete type by mistake.
Bilješke (HR)
Dodaj kratki komentar zasto je polje unknown (iz kojeg izvornog tipa dolazi) kako buduci citatelji ne bi greskom vratili konkretan tip.