5 min read
•Question 7 of 48mediumWhat are Type Guards in TypeScript?
Runtime checks that narrow types.
What You'll Learn
- What type guards are
- Built-in type guards
- Custom type guards
What are Type Guards?
Type guards are runtime checks that narrow the type of a variable within a conditional block.
Built-in Type Guards
code.tsTypeScript
// typeof
function print(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase()); // string
} else {
console.log(value.toFixed(2)); // number
}
}
// instanceof
function logDate(date: Date | string) {
if (date instanceof Date) {
console.log(date.toISOString()); // Date
} else {
console.log(date); // string
}
}
// in operator
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(animal: Fish | Bird) {
if ("swim" in animal) {
animal.swim(); // Fish
} else {
animal.fly(); // Bird
}
}Custom Type Guard
code.tsTypeScript
interface Cat { meow(): void; }
interface Dog { bark(): void; }
// Type predicate
function isCat(animal: Cat | Dog): animal is Cat {
return (animal as Cat).meow !== undefined;
}
function speak(animal: Cat | Dog) {
if (isCat(animal)) {
animal.meow(); // TypeScript knows it's Cat
} else {
animal.bark(); // TypeScript knows it's Dog
}
}