Narrowing
| typeof guards | |
| Truthiness guards | |
| The in operator | |
| instanceof |
typeof guards
A typeof check splits a union into one branch per possible type. Inside the string branch, the value behaves as a string with full method support. The compiler tracks the guard without any extra annotation.
function shout(value: string | number): string {
if (typeof value === "string") {
return value.toUpperCase();
}
return value.toFixed(0);
}
Truthiness guards
An if around the value itself removes null, undefined, zero, and empty string in one move. The surviving branch holds only real content. Guard optional values this way before touching their properties.
function hello(name?: string): string {
if (name) {
return "Hello, " + name;
}
return "Hello, guest";
}
The in operator
The in operator tests whether an object carries a given property name. Each branch of the check exposes a different union member. Use it when siblings share no common tag field.
type Cat = { meow: boolean };
type Dog = { bark: boolean };
function speak(pet: Cat | Dog): string {
if ("meow" in pet) {
return "meow";
}
return "woof";
}
instanceof
The instanceof operator checks which class built the object. The matched branch unlocks that class and its methods. Prefer it for real class hierarchies, not for plain object shapes.
class Cup {
drink(): string {
return "sip";
}
}
function use(item: Cup | string): string {
if (item instanceof Cup) {
return item.drink();
}
return item;
}
Next: Assertions
Article author: Arthur Isaev