Lesson 14 of 56 · Typescript
Type Guards & Discriminated Unions
Duration: 20 minutes
Type Guards
A type guard narrows a union type to a specific member.
function isString(x: unknown): x is string {
return typeof x === "string";
}
function foo(val: string | number) {
if (isString(val)) {
// val is string here
console.log(val.toUpperCase());
} else {
// val is number here
console.log(val.toFixed(2));
}
}
in Operator Guard
type Cat = { kind: "cat"; meow(): void };
type Dog = { kind: "dog"; bark(): void };
type Pet = Cat | Dog;
function speak(pet: Pet) {
if ("meow" in pet) {
pet.meow();
} else {
pet.bark();
}
}
Discriminated Unions (tagged unions)
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle": return Math.PI * s.radius ** 2;
case "square": return s.side ** 2;
}
}