In real life, values often come in several forms. An order number can be 42 or 'AB-17'. A payment is made either by card or in cash. A server returns either data or an error message. You can't describe such cases with a single type — you need “this or that”. For this TypeScript offers union types, and to work with them safely, narrowing.
Union types
The type number | string means “either a number or a string”. With such a value you can only do what works for all members of the union. A number has no toUpperCase method, so this code is an error:
function shout(id: number | string): string {
return id.toUpperCase();
}ids.ts:2:13 - error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
Property 'toUpperCase' does not exist on type 'number'.
2 return id.toUpperCase();
~~~~~~~~~~~NarrowingDefinition
The compiler following your checks (typeof, in, ===, instanceof and so on) and making the value's type more precise inside an if or switch branch. Inside the branch, only the matching member of the union remains.
function formatId(id: number | string): string {
if (typeof id === 'number') {
return `#${id.toString().padStart(4, '0')}`;
}
return id.toUpperCase();
}
console.log(formatId(42));
console.log(formatId('ab-17'));Expected output
#0042 AB-17
if, id is a number; after the return, only string is left.Narrowing tools
| Check | When to use it |
|---|---|
typeof x === 'string' | primitive types: string, number, boolean and so on |
x === null | separating out null or undefined |
'cardNumber' in x | objects with different properties |
x instanceof Date | class instances |
x.kind === 'circle' | discriminated unions (below) |
type Card = { cardNumber: string };
type Cash = { amount: number };
function describePayment(p: Card | Cash): string {
if ('cardNumber' in p) {
return `Card ending in ${p.cardNumber.slice(-4)}`;
}
return `Cash: ${p.amount} AZN`;
}
function greet(name: string | null): string {
if (name === null) {
return 'Hello, guest!';
}
return `Hello, ${name}!`;
}
console.log(describePayment({ cardNumber: 'XXXX-XXXX-XXXX-4821' }));
console.log(describePayment({ amount: 20 }));
console.log(greet(null), greet('Leyla'));Expected output
Card ending in 4821 Cash: 20 AZN Hello, guest! Hello, Leyla!
Discriminated unions
The most powerful technique is to give every member of the union a property with the same name but a different literal value — usually kind or type. This property is called the discriminant. When you write switch (shape.kind), TypeScript knows the exact kind of shape inside each case and allows only its properties.
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; side: number }
| { kind: 'rectangle'; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'square':
return shape.side ** 2;
case 'rectangle':
return shape.width * shape.height;
}
}
const shapes: Shape[] = [
{ kind: 'circle', radius: 1 },
{ kind: 'square', side: 3 },
{ kind: 'rectangle', width: 2, height: 5 },
];
for (const s of shapes) {
console.log(s.kind, area(s).toFixed(2));
}Expected output
circle 3.14 square 9.00 rectangle 10.00
What happens if tomorrow someone on the team adds a triangle to the union? To guarantee that every case is handled, you assign the value to a variable of type never in the default branch. never means “no value at all”: if every case is handled, nothing ever reaches that point. If a case is left unhandled, the compiler tells you at once:
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; side: number }
| { kind: 'triangle'; base: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'square':
return shape.side ** 2;
default: {
const unhandled: never = shape;
return unhandled;
}
}
}area.ts:13:13 - error TS2322: Type '{ kind: "triangle"; base: number; height: number; }' is not assignable to type 'never'.
13 const unhandled: never = shape;
~~~~~~~~~Your own type guards
If you want to move a check into a separate function, returning a plain boolean is not enough — TypeScript doesn't look inside the function to draw conclusions. When you write the return type as value is string, the function becomes a type guard: if it returns true, the compiler trusts that the value is a string. This is especially handy with filter:
function isString(value: unknown): value is string {
return typeof value === 'string';
}
const inputs: unknown[] = ['Baku', 42, 'Ganja', null, 'Shaki'];
const cities = inputs.filter(isString);
console.log(cities.map((city) => city.toUpperCase()).join(', '));Expected output
BAKU, GANJA, SHAKI
cities has the type string[] rather than unknown[], so toUpperCase can be called.Intersection types
If a union means “one of them”, an intersection A & B means “all of them at once”: the value must have all the properties of both types. Intersections make it easy to assemble big types from small, reusable pieces:
type HasId = { id: number };
type HasDate = { createdAt: string };
type Post = HasId & HasDate & { title: string };
const post: Post = { id: 1, createdAt: '2025-09-01', title: 'Hello, TypeScript' };
console.log(`${post.id}: ${post.title} (${post.createdAt})`);Expected output
1: Hello, TypeScript (2025-09-01)
Remember
A | Bmeans “either A or B”; only properties shared by all members can be used directly.typeof,===,inandinstanceofchecks narrow the type inside the branch.- In a discriminated union every member has a literal property like
kind;switchnarrows it perfectly. - Assigning to
neverin thedefaultbranch finds forgotten cases at compile time. - A function returning
value is Tis a type guard;A & Bcombines all properties of both types.