Demo mode — data resets on refresh.
CoursesTypeScript FundamentalsNarrowing and Type Guards

Advanced TypeScript

Narrowing and Type Guards

Type Narrowing

TypeScript narrows types based on control flow. After checking typeof value === "string", TypeScript knows value is a string inside that block.

Type Guards

A type guard is a function that returns a type predicate, telling TypeScript exactly what type a value is.

function isString(val: unknown): val is string { return typeof val === "string" }

Discriminated Unions

A discriminated union is a union of types where each member has a common literal property ("discriminant") that TypeScript can use to narrow.