Union, Intersection & Narrowing
Advanced union types, type narrowing with typeof / instanceof / in, exhaustive checks
Skills taught: ts.union-narrowing, ts.typeof-guard, ts.instanceof-guard, ts.in-guard, ts.exhaustive-check
Type narrowing
// typeof narrowing — works for primitives
function printValue(x: string | number | boolean): void {
if (typeof x === 'string') {
console.log('String:', x.toUpperCase());
} else if (typeof x === 'number') {
console.log('Number:', x.toFixed(2));
} else {
console.log('Boolean:', x);
}
}
printValue('hello'); // String: HELLO
printValue(3.14159); // Number: 3.14
printValue(true); // Boolean: true
// instanceof narrowing — works for class instances
class Dog { bark() { return 'Woof!'; } }
class Cat { meow() { return 'Meow!'; } }
function makeSound(animal: Dog | Cat): string {
if (animal instanceof Dog) return animal.bark();
return animal.meow();
}
console.log(makeSound(new Dog()));
console.log(makeSound(new Cat()));
// in narrowing — checks property existence
interface Admin { role: 'admin'; permissions: string[]; }
interface Viewer { role: 'viewer'; }
function describe(user: Admin | Viewer): string {
if ('permissions' in user) {
return `Admin with ${user.permissions.length} permissions`;
}
return `Viewer: read-only`;
}
// Nullish narrowing — narrow out null/undefined
function greet(name: string | null): string {
if (name === null) return 'Hello, stranger!';
return `Hello, ${name}!`; // name is string here
}
Discriminated unions and exhaustive checks
// Discriminated union — switch on the kind field
type Circle = { kind: 'circle'; radius: number };
type Rectangle = { kind: 'rectangle'; width: number; height: number };
type Triangle = { kind: 'triangle'; base: number; height: number };
type Shape = Circle | Rectangle | Triangle;
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle': return Math.PI * shape.radius ** 2;
case 'rectangle': return shape.width * shape.height;
case 'triangle': return 0.5 * shape.base * shape.height;
default:
// Exhaustive check — shape has type 'never' here
// If you add a new Shape variant and forget a case,
// TypeScript will error on this line:
const _exhaustive: never = shape;
return _exhaustive;
}
}
console.log(area({ kind: 'circle', radius: 5 }).toFixed(2));
// User-defined type guard (predicate)
interface Fish { swim(): void; }
interface Bird { fly(): void; }
function isFish(pet: Fish | Bird): pet is Fish {
return 'swim' in pet;
}
function move(pet: Fish | Bird): void {
if (isFish(pet)) {
pet.swim(); // TypeScript knows it's Fish here
} else {
pet.fly(); // TypeScript knows it's Bird here
}
}
Frequently Asked Questions
What is a user-defined type guard (function x is T)?
A function that returns `x is T` (a type predicate) as its return type. When called, TypeScript narrows x to type T in the true branch. Example: function isString(x: unknown): x is string { return typeof x === 'string' }. This lets you encapsulate a narrowing check and reuse it across your codebase.