Back to series
· 8 min read

Union Types and Intersection Types


I. What Are Union Types

A union type means a value can belong to any one of several types.

Suppose there are two types:

type StringType = string;
type NumberType = number;

A union type can be written as:

type Value = string | number;

Value means the value can be a string or a number.

let value: string | number;

value = "hello";
value = 100;

value = true; // Compile error

Here, | represents a logical choice relationship.

Understood in terms of sets:

A \cup B

It represents all elements that belong to set A or set B.

For a type system, a union type can be understood as the set union of the values allowed by multiple types.

1. Core Characteristics of Union Types

  • A value only needs to satisfy one of the member types in the union.
  • It can represent multiple possible data structures.
  • During type checking, you cannot directly assume the value belongs to one specific member type.
  • You need to determine the current value's specific type through type narrowing.
  • A union type can contain two or more types.

For example:

type ID = string | number | bigint;

function findUser(id: ID) {
    console.log(id);
}

findUser can accept three different types of ID.

2. Union Types and Optional Types

Union types are often used to represent optional values.

type UserName = string | undefined;

It means the value can be a string or undefined.

In TypeScript, you can also use optional properties:

type User = {
    name: string;
    age?: number;
};

When strict null checks are enabled, reading an optional property usually yields a result that includes undefined.

Note the following:

  • T | undefined explicitly states that the type includes undefined.
  • property?: T means the property can be omitted.
  • The two are not fully equivalent when it comes to property existence, assignment checks, and the exact optional property configuration.

II. Type Narrowing of Union Types

A union type contains multiple possible types, so the compiler cannot allow calls to methods of all member types before the specific member is determined.

For example:

function printValue(value: string | number) {
    console.log(value.toUpperCase());
}

This code does not pass type checking.

The reason is:

  • string has toUpperCase().
  • number does not have toUpperCase().
  • The compiler cannot guarantee that value is definitely a string.

You need to narrow the type first.

1. Narrowing with typeof

function printValue(value: string | number) {
    if (typeof value === "string") {
        console.log(value.toUpperCase());
    } else {
        console.log(value.toFixed(2));
    }
}

typeof can check JavaScript's primitive types at runtime and helps TypeScript infer the type within a branch.

2. Narrowing with instanceof

class Dog {
    bark() {}
}

class Cat {
    meow() {}
}

function handleAnimal(animal: Dog | Cat) {
    if (animal instanceof Dog) {
        animal.bark();
    } else {
        animal.meow();
    }
}

instanceof is suitable for checking objects that have a runtime constructor identity.

Note that interfaces and type aliases are erased after TypeScript compilation, so they cannot be used directly as the right-hand operand of instanceof.

3. Narrowing with the in Operator

```typescript type Dog = { bark: () => void; }; type Cat = { meow: () => void; }; function handleAnimal(animal: Dog | Cat) { if ("bark" in animal) { animal.bark(); } else { animal.meow(); } } ```

in can check whether an object has a certain property, and it participates in type narrowing.

However, if multiple member types may all have that property, the narrowed result may still be a union type.

4. Using a Discriminant Property (Discriminated Union)

Discriminated unions are a very important modeling technique in TypeScript.

type Success = {
    status: "success";
    data: string;
};

type Failure = {
    status: "failure";
    error: string;
};

type Result = Success | Failure;

Distinguish the different members through the common discriminant property status:

function handleResult(result: Result) {
    if (result.status === "success") {
        console.log(result.data);
    } else {
        console.error(result.error);
    }
}

Advantages of discriminated unions:

  • The type structure is clear.
  • Branch handling is safe.
  • Illegal state combinations are harder to express.
  • Well suited to modeling API responses, state machines, and business flows.

5. Union Type Narrowing Flow

flowchart TD
    A["Receive a union-typed value"] --> B["Analyze the possible member types"]
    B --> C["Perform type checks"]
    C --> D{"Concrete member determined?"}
    D -->|"Yes"| E["Narrow to the corresponding type"]
    D -->|"No"| F["Keep the union type"]
    E --> G["Access operations supported by that type"]
    F --> H["Continue checking or handle common capabilities"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

3. What Are Intersection Types

An intersection type means that a value simultaneously satisfies the constraints of multiple types.

Suppose there are two types:

type Person = {
    name: string;
};

type Employee = {
    employeeId: number;
};

You can combine them with &:

type Staff = Person & Employee;

At this point Staff contains the property requirements of both types:

const staff: Staff = {
    name: "Alice",
    employeeId: 1001
};

If any one of the required properties is missing, the type requirements of Staff cannot be satisfied.

Understood from a set perspective:

A \cap B

It represents the elements that belong to both set A and set B.

For a type system, an intersection type means a value must satisfy multiple type constraints at the same time.

1. Core Characteristics of Intersection Types

  • A value must satisfy the requirements of all member types at the same time.
  • Multiple object types can be combined.
  • The capabilities of an existing type can be extended.
  • Multiple interface constraints can be merged.
  • When multiple types conflict, the result may be a type that is hard to use or even impossible to construct.

For example:

type Timestamped = {
    createdAt: Date;
};

type Identifiable = {
    id: string;
};

type Entity = Timestamped & Identifiable;

Entity has both:

  • A createdAt property.
  • An id property.

Intersection types are particularly suitable for compositional type design.

2. Intersection Types and Interface Inheritance

Both intersection types and interface inheritance can combine members from multiple types, but their semantics and applicable scenarios differ.

Intersection types:

type Person = {
    name: string;
};

type Employee = {
    employeeId: number;
};

type Staff = Person & Employee;

Interface inheritance:

interface Person {
    name: string;
}

interface Employee {
    employeeId: number;
}

interface Staff extends Person, Employee {}

Comparison:

Dimension Intersection Types Interface Inheritance
Syntax A & B extends A, B
Composing object types Supported Supported
Composing type aliases Supported Cannot directly extend arbitrary union types
Property conflicts May form complex intersection results Compatibility is usually checked at declaration time
Usage Type composition expression Declaring an interface hierarchy
Use cases Flexible type composition Stable object contracts

IV. Type Composition Mechanisms of Intersection Types

1. Merging Object Properties

When properties of two object types do not conflict, an intersection type usually manifests as a combination of the property requirements.

type A = {
    id: number;
};

type B = {
    name: string;
};

type C = A & B;

Equivalently, this can be understood as:

type C = {
    id: number;
    name: string;
};

This equivalence is understood in terms of the effect of using the properties; it does not mean that the compiler necessarily rewrites the intersection type directly into an ordinary object literal.

2. Intersection of Identical Properties

If two types have the same property, the relationship between the property types must be considered further.

type A = {
    value: string | number;
};

type B = {
    value: string;
};

type C = A & B;

Here, value must satisfy both:

  • string | number
  • string

The resulting usable type is equivalent to:

type C = {
    value: string;
};

Because string is itself part of string | number.

This can be understood from the perspective of type sets:

(string \cup number) \cap string = string

3. Intersection of Incompatible Properties

If two property types have no common usable value, the intersection result may become never.

type A = {
    value: string;
};

type B = {
    value: number;
};

type C = A & B;

In this case, value must be both a string and a number.

For TypeScript's primitive types string and number, there is no ordinary value that satisfies both at the same time, so:

type Value = string & number;
// never

In object types, a conflicting property may cause that property to become never; whether the entire object type is further reduced to never also depends on the form of the property conflict and the compiler's type simplification rules.

For example:

type A = {
    value: string;
};

type B = {
    value: number;
};

type C = A & B;

const data: C = {
    value: "hello" // Compilation error
};

Such conflicts can easily become hidden problems in complex type combinations.

4. Accumulation of Constraints in Intersection Types

Intersection types can combine not only properties but also function signatures and other structural constraints.

type HasId = {
    id: string;
};

type HasName = {
    name: string;
};

type HasTimestamp = {
    createdAt: Date;
};

type RecordEntity = HasId & HasName & HasTimestamp;

As intersection types combine, the type constraints keep accumulating.

flowchart TD
    A["Type A: HasId"] --> D["Intersection combination"]
    B["Type B: HasName"] --> D
    C["Type C: HasTimestamp"] --> D
    D --> E["RecordEntity"]
    E --> F["Must satisfy all property constraints"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

V. The Core Difference Between Union Types and Intersection Types

Although both union types and intersection types are used to combine types, they express two different kinds of logical relationships.

Suppose:

type A = {
    name: string;
};

type B = {
    age: number;
};

Union type:

type Union = A | B;

This means a value satisfies one of the types, A or B.

Intersection type:

type Intersection = A & B;

This means a value satisfies both A and B.

Comparison dimension Union type A \| B Intersection type A & B
Core semantics Satisfies one of them Satisfies all of them
Set relationship Union Intersection
Logical interpretation OR AND
Type requirement Satisfies at least one member Must satisfy all members
Typical use Multiple possible states Combination of multiple capabilities
Type narrowing Usually required Usually no need to distinguish members
Type conflict Preserves the different possibilities May narrow to never

1. Understanding the Structure of a Union Type

type A = {
    name: string;
};

type B = {
    age: number;
};

type U = A | B;

An object only needs to satisfy one of the member types:

const a: U = {
    name: "Alice"
};

const b: U = {
    age: 18
};

const c: U = {
    name: "Alice",
    age: 18
};

Note that TypeScript's structural type system allows extra properties to exist on a variable, so c can also be assigned to U.

When an object literal is passed directly, excessive extra properties may trigger Excess Property Checking. This is an additional static checking mechanism and should not be understood as meaning that a union type only permits the properties of a single member.

2. Understanding the Structure of an Intersection Type

type I = A & B;

The object must have the properties of both types at the same time:

const value: I = {
    name: "Alice",
    age: 18
};

If any one property is missing, the intersection type cannot be satisfied.

VI. The Algebraic Relationship Between Union Types and Intersection Types

From the perspective of type sets, union and intersection can be understood as the set union and set intersection of types.

1. Basic Laws of Union

A \cup B = B \cup A

The order of the union does not affect the set semantics.

(A \cup B) \cup C = A \cup (B \cup C)

Union types satisfy the associative property.

A \cup A = A

Union with the same type still yields the original type.

2. Basic Rules of Intersection

A \cap B = B \cap A

The order of intersection does not affect set semantics.

(A \cap B) \cap C = A \cap (B \cap C)

Intersection types satisfy associativity.

A \cap A = A

Intersecting the same type with itself still yields the original type.

3. Distributive Laws

Union and intersection of type sets satisfy the distributive laws:

A \cap (B \cup C) = (A \cap B) \cup (A \cap C)
A \cup (B \cap C) = (A \cup B) \cap (A \cup C)

TypeScript's conditional types also exhibit distributive behavior related to union types, but note: TypeScript's type system is not a system defined entirely in terms of mathematical set operations.

In particular:

  • any, unknown, and never have special rules.
  • Structural type compatibility is not the same as simple set equality.
  • The distributive behavior of conditional types is subject to explicit syntactic conditions.
  • Conflicting object properties may cause a type to be reduced to never.

Therefore, set algebra is a useful aid to understanding, but it should not be used as a direct substitute for the type rules of a specific language.

7. The Role of never and unknown in Unions and Intersections

never and unknown are important foundations for understanding TypeScript's union and intersection types.

1. never: The Bottom Type

never represents the type of values that cannot possibly exist.

type A = string | never;
type B = string & never;

Results:

type A = string;
type B = never;

Corresponding relations:

A \cup never = A
A \cap never = never

never is commonly used to:

  • Represent functions that never return normally.
  • Represent states that can never occur.
  • Check whether a union type has been handled exhaustively.
  • Perform filtering and branch computation in conditional types.

2. unknown: The Safe Top Type

unknown can represent any value, but it must be type-checked before use.

let value: unknown;

value = "hello";
value = 100;

Union:

type A = string | unknown;
// unknown

Intersection:

type B = string & unknown;
// string

Corresponding relations: