Question presented to candidate:
"TypeScript lets you write if (typeof x === 'string') and then call string methods on x inside the block. What is that mechanism called, which checks does the compiler understand, and how do you write your own type guard?"
What a strong answer should cover:
- Narrowing is control-flow analysis: a variable has a declared type and, at each point in the code, a narrower current type based on the checks and assignments that came before
- The built-in guards:
typeof, truthiness,===/!==(includingnullchecks),instanceof,Array.isArray,in, and discriminant property checks; early returns narrow the rest of the function - Classic traps:
typeof null === "object", truthiness also drops""and0, narrowing of mutable values is not trusted inside callbacks - User-defined type guards (
x is T): the false branch narrows too,filter(isX)gives a narrowed array, and the compiler trusts the predicate blindly, so a wrong guard is a real bug - Related tools and versions: assertion functions (
asserts x is T), 5.4 keeping narrowing in closures after the last assignment, 5.5 inferring predicates
Code / implementation expected: Yes β a function that narrows a union with built-in checks, plus one hand-written x is T guard.