Skip to content

Type Guard

Medium — good to knowGeneral Dev

ELI5 — The Vibe Check

A type guard is like a bouncer at a club checking IDs. Before your code enters the VIP section, the guard checks 'are you a string or a number?' and TypeScript remembers the answer so you don't get type errors inside.

Real Talk

A TypeScript expression that performs a runtime check to narrow the type of a variable within a conditional block. Type guards use typeof, instanceof, 'in' operator, or custom type predicate functions (paramName is Type) to help the compiler understand the exact type at a specific point in code.

Show Me The Code

function isString(value: unknown): value is string {
  return typeof value === 'string';
}

function process(input: string | number) {
  if (isString(input)) {
    // TypeScript knows input is string here
    console.log(input.toUpperCase());
  } else {
    // TypeScript knows input is number here
    console.log(input.toFixed(2));
  }
}

When You'll Hear This

"Write a type guard for your API responses so TypeScript knows the shape after validation." / "Custom type guards with 'is' predicates are cleaner than casting everywhere."

Made with passive-aggressive love by manoga.digital. Powered by Claude.