Sobes.tech
Middle+

Practical task: write a TypeGuard to determine the type of animal (Dog or Cat)

sobes.tech AI

Answer from AI

TypeGuard in TypeScript allows you to refine the type of an object at runtime so that the compiler understands which specific type is being used.

Example of a TypeGuard to determine whether an animal is a dog or a cat:

interface Dog {
  bark(): void;
}

interface Cat {
  meow(): void;
}

function isDog(animal: Dog | Cat): animal is Dog {
  return (animal as Dog).bark !== undefined;
}

// Usage:
function makeSound(animal: Dog | Cat) {
  if (isDog(animal)) {
    animal.bark();
  } else {
    animal.meow();
  }
}

Here, the isDog function checks for the presence of the bark method, which allows TypeScript to narrow the type within the conditional block.