typescript / intermediate
Snippet
Benutzerdefinierte Type-Guards
Ein Type-Guard ist eine Funktion, die ein Typ-Prädikat ('pet is Fish') zurückgibt. Es ermöglicht TypeScript, den Typ eines Objekts innerhalb eines Codeblocks nach einer Laufzeitprüfung einzugrenzen.
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}}
Erklärung
1
pet is Fish
Der Rückgabetyp 'pet is Fish' teilt dem Compiler mit: Wenn die Funktion 'true' zurückgibt, ist 'pet' definitiv ein Fisch.