Skip to content

Type Guard

In one line

A type guard is a check (like typeof or a user-defined function) that narrows a value's type within a conditional block, enabling type-safe access to type-specific properties.

In simple words

A type guard is a runtime check that tells TypeScript to narrow a type. After the check passes, TypeScript knows the value is a more specific type, and lets you access type-specific properties.

Built-in type guards include typeof (for primitives), instanceof (for classes), and in (for property existence). You can also write user-defined type guards using the x is T predicate.

For example, if value is string | number, you can't call value.toUpperCase() directly. But inside if (typeof value === "string"), TypeScript narrows value to string and the call is allowed.

Example

typescript
// Built-in type guard with typeof
function process(x: string | number) {
  if (typeof x === "string") {
    return x.toUpperCase(); // x narrowed to string
  }
  return x.toFixed(2); // x narrowed to number
}

// User-defined type guard
function isString(x: unknown): x is string {
  return typeof x === "string";
}

typeof narrows x in each branch. The 'is' predicate creates a user-defined guard.

Related terms

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary