Functions and Type NarrowingLesson 3.3
Union types and type narrowing in TypeScript
union type syntax, typeof narrowing, instanceof narrowing, in operator narrowing, narrowing pitfalls, control flow analysis
Union types
A union type accepts any of its members. TypeScript tracks which branch of a conditional is taken โ this is control flow analysis:
function format(input: string | number): string {
if (typeof input === "string") {
return input.toUpperCase(); // input is string here
}
return input.toFixed(2); // input is number here
}instanceof narrowing
function process(value: Date | string) {
if (value instanceof Date) {
return value.toISOString(); // Date
}
return value; // string
}in operator narrowing
interface Cat { meow(): void; }
interface Dog { bark(): void; }
function makeNoise(animal: Cat | Dog) {
if ("meow" in animal) {
animal.meow(); // Cat
} else {
animal.bark(); // Dog
}
}TypeScript's control flow analysis handles all standard narrowing patterns. After an if block that returns or throws, the type in the else branch is automatically narrowed โ you do not need explicit else when the if branch exits.
