Type Guard (TypeScript)

A type guard is a runtime check that narrows a value to a more specific type, such as `typeof x === "string"` or `"id" in obj`. Inside the check, TypeScript treats the value as that narrower type.

TypeScript

When you have a union type, you usually can't use a value safely until you know which member it is. A type guard performs the check, and TypeScript 'narrows' the type within that branch so the right properties and methods become available.

Besides `typeof`, `instanceof`, and the `in` operator, you can write your own user-defined type guard — a function whose return type is `value is SomeType`.

Examples

TypeScript

function len(x: string | string[]): number {
  if (typeof x === "string") {
    return x.length;       // x narrowed to string
  }
  return x.length;         // x narrowed to string[]
}

console.log(len("hi"), len(["a", "b"]));

Output:

2 2

Learn it in a lesson

See also

Back to the Dictionary