Skip to content
TypeScript

Type guards

Fonctions de type guard personnalisées.

#type-guard#type-narrowing

Code

typescript
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();
}