Rules Hub
Coding Rules Library
← Back to all rules
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
fullstack ruleP2stack specificStack: typescript
typescriptnarrowingtype-guardsvalidation
Use a const-asserted array plus a type guard to narrow a string against allowed values
Array.includes on an `as const` array won't narrow a plain string in TypeScript; add a small type guard so the check both validates and narrows.
PR: hegnar-web · org-mining-hist-2026-06Created: Jun 19, 2026
Bad example
Old codetypescript
| 1 | const sources = ['all', 'fa', 'tdn'] as const; |
| 2 | if (!sources.includes(source)) return; // TS error: string not assignable |
Explanation (EN)
Objašnjenje (HR)
Good example
New codetypescript
| 1 | const sources = ['all', 'fa', 'tdn'] as const; |
| 2 | type Source = typeof sources[number]; |
| 3 | const isSource = (v: string): v is Source => (sources as readonly string[]).includes(v); |
| 4 | if (!isSource(source)) return; |
| 5 | // source is now narrowed to Source |
Explanation (EN)
Objašnjenje (HR)