typescript / intermediate
Snippet
User-Defined Type Guards
A type guard is a function that returns a type predicate ('pet is Fish'). It allows TypeScript to narrow down the type of an object within a specific code block after a runtime check.
snippet.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
interface Bird { fly: () => void; }interface Fish { swim: () => void; }function isFish(pet: Bird | Fish): pet is Fish {return (pet as Fish).swim !== undefined;}function move(pet: Bird | Fish) {if (isFish(pet)) {pet.swim(); // TypeScript knows it's a Fish} else {pet.fly(); // TypeScript knows it's a Bird}}
Breakdown
1
pet is Fish
The return type 'pet is Fish' tells the compiler that if the function returns true, 'pet' is definitely a Fish.