Sobes.tech
Middle+

What is a type guard in TypeScript?

sobes.tech AI

Answer from AI

Type guard in TypeScript is a way to narrow down the type of a variable within a conditional block so that the compiler understands which specific type we are working with. This allows safe access to properties or methods specific to that type.

Example of a type guard using the typeof operator:

function example(value: string | number) {
  if (typeof value === "string") {
    // Here, value is a string
    console.log(value.toUpperCase());
  } else {
    // Here, value is a number
    console.log(value.toFixed(2));
  }
}

You can also create custom type guards — functions that return value is Type:

type Fish = { swim: () => void };
type 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(); // TypeScript knows that pet is Fish
  } else {
    pet.fly(); // pet is Bird
  }
}

Thus, a type guard helps work safely with union types and improves type checking during compilation.