Using Type Guards To Tell TypeScript, If An Object Is Of A Specific Type
[!INFO]-
topic: π¦ TypeScript
links: Defining union types
source: TypeScript course by the native web
tags: #permanent-noteΒ #published
Last Modified:
=dateformat(this.file.mtime, "MMM. dd, yyyy - HH:mm")
When working with union types and want to access a function, that only some of the union types support, you have to tell TypeScript, if the object is of the corresponding type. To accomplish this, you can create a function, that returns true
or false
depending on if the object matches the desired class or interface, but the return type of the function is not boolean, it is a specific type guard syntax variable is class
.
In this case, have different types of animals and want to make sure, that the animal is a Cat or a Fish, so we return animal is Cat
or animal is Fish
.
class Cat {
public breathe (): void {}
public meow (): void {}
}
// Type guard
const isCat = function (animal: Cat | Fish): animal is Cat {
return Boolean((animal as any).meow);
}
class Fish {
public breathe (): void {}
public swim (): void {}
}
// Type guard
const isFish = function (animal: Cat | Fish): animal is Fish {
if ((animal as any).swim) {
return true;
}
return false;
};
const getSomeAnimal = function (): Cat | Fish {
return new Fish();
}
const animal = getSomeAnimal();
animal.breathe();
if (isFish(animal)) {
animal.swim();
}
export {};