How TypeScript thinks · core
Narrowing and type guards
Narrowing is how TypeScript follows your runtime checks (typeof, instanceof, in, equality, truthiness, custom guards) to a more specific type inside each branch.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Built-in guards:
typeof x === 'string',x instanceof Date,'key' in obj,x === null,Array.isArray(x), truthiness. - A user-defined guard returns
value is T:function isUser(x: unknown): x is User. TypeScript trusts it, so it must be correct. - Assertion functions
asserts x is Tnarrow everything after the call; they must throw when the check fails. - Since TS 5.5, a function like
x => x !== nullis inferred as a type predicate, soarr.filter(x => x !== null)gives a non-null array. - Narrowing is lost across callbacks for
letvariables that may be reassigned; copy to aconstfirst.
The red pen
Common traps: mistake → fix
Mistake: "a type guard checks the type for you"
Fix: it only checks what your code checks; a wrong guard lies to the compiler.
Mistake: "typeof null is 'null'"
Fix: it is 'object', so
typeof x === 'object'does not exclude null.
Easy to hard
Questions interviewers ask, easy to hard
- What ways do you know to narrow a union?
- What is a user-defined type guard and what is the risk?
- Why does
.filter(Boolean)not always narrow, and what changed in TS 5.5?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.