Type Guards & Narrowing in TypeScript

From the TypeScript cheat sheet · Advanced Types · verified Jul 2026

Type Guards & Narrowing

All the ways to narrow types in conditional blocks

typescript
// typeof
if (typeof x === "string") { x.toUpperCase(); }

// instanceof
if (err instanceof Error) { err.message; }

// in operator
if ("email" in user) { user.email; }

// Custom type predicate
function isString(x: unknown): x is string {
  return typeof x === "string";
}
💡 Discriminated unions with a "kind" field + switch is the most type-safe branching pattern
⚡ Custom type predicates (is keyword) let you create reusable narrowing functions
📌 The assertNever pattern catches missing switch cases at compile time — essential for unions
🟢 TypeScript narrows automatically with typeof, instanceof, in, truthiness, and equality checks

More TypeScript tasks

Back to the full TypeScript cheat sheet