TypeScript Narrowing
Show how TypeScript narrowing works with typeof, in, discriminated unions, and why any undermines it.
Answers use simple, clear English.
Quick interview answer
Control-flow analysis narrows types after checks: typeof x === 'string', 'prop' in obj, or switch on a shared kind/tag field for discriminated unions. Avoid any — it opts out of checking and poisons inference. Prefer unknown + narrowing for external data.
Detailed answer
Control-flow analysis narrows types after checks: typeof x === 'string', 'prop' in obj, or switch on a shared kind/tag field for discriminated unions. Avoid any — it opts out of checking and poisons inference. Prefer unknown + narrowing for external data.
Real example & use case
API response parsed as unknown then narrowed before use in UI.
Pros & cons
Pros: safer refactors. Cons: poor types at boundaries force awkward casts if validation is skipped.
Code example
type Shape =
| { kind: 'circle'; r: number }
| { kind: 'square'; s: number };
function area(s: Shape): number {
switch (s.kind) {
case 'circle': return Math.PI * s.r ** 2;
case 'square': return s.s ** 2;
}
}Practice code · typescript (view only · no execution)
type Shape =
| { kind: 'circle'; r: number }
| { kind: 'square'; s: number };
function area(s: Shape): number {
switch (s.kind) {
case 'circle': return Math.PI * s.r ** 2;
case 'square': return s.s ** 2;
}
}