Codectionary / Developer documentation / TypeScript

Union and Intersection Types

A union type (A | B) means a value can be either type A or type B. An intersection type (A & B) means a value must satisfy both A and B simultaneously, combining their members into one type. Unions are common for values with a few valid states; intersections are common for combining smaller, focused types into a larger one.

Syntax

type Union = TypeA | TypeB;
type Intersection = TypeA & TypeB;

Examples

Union Types

A value that can be one of several specific types.

type ID = string | number;

function printId(id: ID) {
  console.log(`ID: ${id}`);
}

printId(101);      // OK
printId("abc-123"); // OK
// printId(true);    // Error - boolean is not part of the union

Intersection Types

Combining multiple types into one that has all of their members.

type Named = { name: string };
type Aged = { age: number };

type Person = Named & Aged; // must have BOTH name and age

const person: Person = {
  name: "Alice",
  age: 25
};
// A value missing either "name" or "age" would fail to type-check

Best practices

  • Use union types to model a value with a small, known set of valid shapes or states, like a status field
  • Use intersection types to compose smaller, reusable type fragments into a larger, complete type
  • Combine unions with discriminant properties (a shared "kind" or "type" field) to enable clean type narrowing in conditional logic
  • Be cautious intersecting types with conflicting property types - the result can resolve to never for that property, which is easy to miss

At a glance

Purpose
Static types for JavaScript
File extension
.ts ยท .tsx
Runs in
Compiled to JavaScript
Usually used with
JavaScript and its ecosystem

Specifications & further reading

Related TypeScript documentation