Skip to the solution
MediumFrontend12 min read

What is type narrowing and what are type guards?

1.1k views

The problem

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, === / !== (including null checks), instanceof, Array.isArray, in, and discriminant property checks; early returns narrow the rest of the function
  • Classic traps: typeof null === "object", truthiness also drops "" and 0, 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.

  • narrowing
  • guards

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptBuilt-in guards: typeof, equality, Array.isArray and early returns
TypeScriptUser-defined type guards with x is T, and a guard that lies
TypeScriptWhen narrowing survives into callbacks, and when it does not

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 16 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What are generic constraints?

Continue