Unions and narrowing

Combine types with `|` and `&`, narrow them with `typeof`, `in` and comparisons, build discriminated unions and write your own type guards.

  • Intermediate
  • 18 min
  • 10 questions
  • Lesson 5 of 8

In this lesson you will learn

  • Write and tell apart union (A | B) and intersection (A & B) types
  • Narrow a type with typeof, in, === and null checks
  • Build a discriminated union and check that every case is handled with never
  • Write a type guard of the form value is T

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:

TypeScript
function shout(id: number | string): string {
  return id.toUpperCase();
}
Text
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.

TypeScript
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
Inside the if, id is a number; after the return, only string is left.

Sign up free to keep reading

The rest of the lesson, the quiz and your notes open with an Educora account. Signing up takes a minute, and your progress is saved on all your devices.

Narrowing tools

CheckWhen to use it
typeof x === 'string'primitive types: string, number, boolean and so on
x === nullseparating out null or undefined
'cardNumber' in xobjects with different properties
x instanceof Dateclass instances
x.kind === 'circle'discriminated unions (below)
TypeScript
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.

TypeScript
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:

TypeScript
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;
    }
  }
}
Text
area.ts:13:13 - error TS2322: Type '{ kind: "triangle"; base: number; height: number; }' is not assignable to type 'never'.

13       const unhandled: never = shape;
               ~~~~~~~~~
The error message shows exactly which case was forgotten — the triangle.

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:

TypeScript
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
Thanks to the guard, 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:

TypeScript
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 | B means “either A or B”; only properties shared by all members can be used directly.
  • typeof, ===, in and instanceof checks narrow the type inside the branch.
  • In a discriminated union every member has a literal property like kind; switch narrows it perfectly.
  • Assigning to never in the default branch finds forgotten cases at compile time.
  • A function returning value is T is a type guard; A & B combines all properties of both types.
Spotted a mistake or something inaccurate in this lesson?

Check yourself

10 questions. Every correct answer earns XP.

Question 1 / 10

Question 1 / 10. Inside if (typeof id === 'number') { ... }, what is the type of the parameter id: number | string?