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

Continue with TypeScript

Save the full cheat sheet or work through every related task.

More TypeScript tasks

Back to the full TypeScript cheat sheet