TypeScript Type Narrowing: typeof, in, Discriminated Unions and Type Guards
How TypeScript narrows union types: typeof, instanceof, in, equality checks, discriminated unions, custom type guards, assertion functions.
Published December 6, 2026
Union types like string | number or Success | Failure are everywhere in TypeScript, and to use them safely you need narrowing: TypeScript's ability to understand that inside a certain branch, a value can only be one member of the union. Mastering narrowing is the difference between fighting the compiler with casts and letting it prove your code correct.
The concept
TypeScript narrows through control flow analysis. Checks like typeof x === "string", x instanceof Date, "error" in result, x === null and truthiness checks all refine the type inside the branch and after early returns. Discriminated unions take this further: give each variant a literal kind field, and switching on it narrows to the exact variant.
When built-in checks are not enough, write user-defined type guards (functions returning value is Type) or assertion functions (asserts value is Type) that throw if the check fails. An exhaustive switch with a never check makes the compiler flag every place you forgot to handle when a new variant is added.
Narrowing techniques
| Technique | Example | Narrows to |
|---|---|---|
| typeof | typeof v === "string" | string |
| instanceof | err instanceof HttpError | HttpError |
| in | "data" in res | variant with data |
| Equality / literal | res.status === "ok" | variant with status "ok" |
| Truthiness | if (user) | excludes null/undefined |
| Custom guard | isUser(v): v is User | User |
Discriminated unions
Exhaustiveness checking
- Model variants with a literal kind/type field
- Switch on the discriminant
- Handle each case
- Add default: assertNever(x) for exhaustiveness
Practical examples
Discriminated union with exhaustive switch
Adding a variant makes the default case a compile error.
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'rect'; width: number; height: number }
function assertNever(x: never): never { throw new Error(`Unhandled: ${JSON.stringify(x)}`) }
function area(s: Shape): number {
switch (s.kind) {
case 'circle': return Math.PI * s.radius ** 2
case 'rect': return s.width * s.height
default: return assertNever(s)
}
}User-defined type guard
Narrow unknown data after runtime checks.
interface User { id: string; email: string }
function isUser(v: unknown): v is User {
return typeof v === 'object' && v !== null && typeof (v as any).id === 'string' && typeof (v as any).email === 'string'
}
const data: unknown = await res.json()
if (isUser(data)) console.log(data.email)Assertion function
Throw if invalid; narrowed afterwards.
function assertDefined<T>(v: T, msg = 'value missing'): asserts v is NonNullable<T> {
if (v === null || v === undefined) throw new Error(msg)
}
const el = document.getElementById('app')
assertDefined(el)
el.textContent = 'ready' // HTMLElement, not HTMLElement | nullCommon mistakes
- Using as casts instead of narrowing.
- Type guards that do not actually check what they claim.
- Optional boolean flags instead of a discriminant field.
- Missing exhaustiveness checks, so new variants are silently ignored.
Key takeaways
- Control flow analysis narrows unions after checks.
- Discriminated unions are the cleanest way to model variants.
- Custom guards and assertion functions handle unknown data.
- Use never-based exhaustiveness checks.
FAQ
Why does narrowing not work inside callbacks?
TypeScript cannot be sure the value has not changed by the time the callback runs; copy it into a const first.
Should I use type guards or zod?
Schema libraries like zod generate both runtime checks and types, and are more reliable for complex external data than handwritten guards.
What does the never type mean?
A type with no values; reaching code where a variable is never means all cases were handled.