Skip to content

TypeScript Type Guards API

TypeScript type guards for narrowing types at runtime.

1 class · 4 methods

Type Guards

4 methods

Runtime checks that narrow types in conditional branches.

typeof x === 'string'

Narrow primitive types using the typeof operator. Recognized: 'string', 'number', 'boolean', 'bigint', 'symbol', 'undefined', 'object', 'function'.

Parameters

NameTypeDescription
xanyValue to narrow.

Returns

boolean

Example

typescript
function len(x: string | number): number {
  if (typeof x === 'string') {
    return x.length;  // x: string
  }
  return Math.abs(x);  // x: number
}
x instanceof Class

Narrow to an instance type by checking the prototype chain.

Parameters

NameTypeDescription
xanyValue to narrow.
ClassconstructorClass constructor to check against.

Returns

boolean

Example

typescript
function handle(e: Error | Date) {
  if (e instanceof Error) {
    console.log(e.message);  // e: Error
  } else {
    console.log(e.getTime());  // e: Date
  }
}
'key' in obj

Narrow a union type by checking for the presence of a property.

Parameters

NameTypeDescription
keystringProperty name to check.
objobjectObject to check.

Returns

boolean

Example

typescript
type Cat = { meow: () => void };
type Dog = { bark: () => void };
function speak(animal: Cat | Dog) {
  if ('meow' in animal) animal.meow();   // animal: Cat
  else animal.bark();                    // animal: Dog
}
function isX(x: any): x is T

User-defined type guard. The 'x is T' return type predicate triggers narrowing when the function returns true.

Parameters

NameTypeDescription
xanyValue to test.

Returns

x is T

Example

typescript
function isString(x: any): x is string {
  return typeof x === 'string';
}
function upper(x: unknown) {
  if (isString(x)) {
    return x.toUpperCase();  // x: string
  }
  return String(x);
}