interface Cat { kind: 'cat'; meow(): void }
interface Dog { kind: 'dog'; bark(): void }
type Animal = Cat | Dog;
function isCat(a: Animal): a is Cat {
return a.kind === 'cat';
}
function makeSound(a: Animal) {
if (isCat(a)) {
a.meow(); // a is narrowed to Cat
} else {
a.bark(); // a is narrowed to Dog
}
}
// Works for arbitrary "is non-null" checks too:
function isPresent<T>(x: T | null | undefined): x is T {
return x !== null && x !== undefined;
}
const nums: number[] = [1, null, 2, undefined, 3].filter(isPresent);
// nums: number[] — null/undefined filtered out at the type level
Create a free account and build your private vault. Share publicly whenever you want.