Skip to content
TypeScript

Type Guards

Custom type guard functions.

By EZ4Code Team
type-guardtype-narrowing

Code

function isString(val: unknown): val is string {
  return typeof val === "string";
}

function isArray<T = unknown>(val: unknown): val is T[] {
  return Array.isArray(val);
}

interface Fish { swim(): void; }
interface Bird { fly(): void; }

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

function move(pet: Fish | Bird) {
  if (isFish(pet)) pet.swim();
  else pet.fly();
}

Explanation

Type guards narrow the type scope by returning type predicates.

More TypeScript Snippets