Skip to main content

TypeScript Union vs Intersection Types: What A | B and A & B Really Mean

Updated 10 min readMarkdown
TypeScript Union vs Intersection Types: What A | B and A & B Really Mean

What do A | B and A & B mean?

A union A | B means "a value of type A or type B". An intersection A & B means "a value that is type A and type B at the same time".

The names are easy to read, but the results often surprise people. A union of two object types gives you fewer properties you can safely use, and an intersection gives you more. And with intersections, some combinations quietly turn into never.

In this post I will explain both with small examples, and then go through the confusing cases one by one. I will use the Player example again.

Union types: one of several

A union says that a value can be one of the listed types.

type Id = string | number;

let id: Id = 'abc';
id = 42;     // OK
id = true;
// Error: Type 'boolean' is not assignable to type 'Id'

The important rule: TypeScript does not know which type you have right now, so it allows only what is safe for every member of the union.

function printId(id: Id) {
    console.log(id.toString()); // OK, both string and number have toString

    console.log(id.toUpperCase());
    // Error: Property 'toUpperCase' does not exist on type 'number'
}

To use something that only one member has, you need to narrow the type first:

function printId(id: Id) {
    if (typeof id === 'string') {
        console.log(id.toUpperCase()); // id is string here
    } else {
        console.log(id.toFixed(2));    // id is number here
    }
}

The same works for objects. Look at this union of two object types:

type Dog = { name: string; bark(): void };
type Fish = { name: string; swim(): void };
type Pet = Dog | Fish;

function describe(pet: Pet) {
    console.log(pet.name); // OK, both have name

    pet.bark();
    // Error: Property 'bark' does not exist on type 'Fish'

    if ('bark' in pet) {
        pet.bark(); // OK, pet is Dog here
    }
}

One more thing that surprises people: a union is inclusive, not exclusive. A value that has the properties of both types is also valid:

const weirdPet: Pet = {
    name: 'Nemo',
    bark() {},
    swim() {},
};
// OK, this object is both a Dog and a Fish, so it fits the union

So A | B means "A, or B, or both", not "exactly one of them".

Intersection types: all at once

An intersection says that a value must satisfy all the listed types at the same time. For objects, this means combining their properties into one bigger type.

type Named = { nickname: string };
type Leveled = { level: number };

type Player = Named & Leveled;

const neo: Player = { nickname: 'Neo', level: 1 };

const broken: Player = { nickname: 'Trinity' };
// Error: Property 'level' is missing in type '{ nickname: string; }'

The Player type needs both nickname and level. It is like building a type from small pieces.

A very common use is adding something to an existing type without changing it:

type WithId<T> = T & { id: number };

type Saved = WithId<Named & Leveled>;
// { nickname: string } & { level: number } & { id: number }

const saved: Saved = { id: 1, nickname: 'Neo', level: 1 };

Why it feels backwards

Many people expect | to give more and & to give less. For object properties it is the opposite, and this is the source of most confusion.

The trick is to think about sets of values, not properties:

  • A | B is the bigger set. It contains every value of A and every value of B. Because it is bigger, TypeScript knows less about each value, so fewer properties are safe to use.
  • A & B is the smaller set. It contains only values that are both A and B. Because it is smaller, TypeScript knows more about each value, so you can use the properties of both.
type Dog = { name: string; bark(): void };
type Fish = { name: string; swim(): void };

declare const either: Dog | Fish;
either.name;   // OK, only the shared property is safe
either.bark(); // Error

declare const both: Dog & Fish;
both.name;     // OK
both.bark();   // OK
both.swim();   // OK, it can do everything

Confusing case 1: the same property with different types

What happens when you intersect two object types that have the same property with different types?

type A = { id: string; name: string };
type B = { id: number; age: number };

type C = A & B;

The type C has the properties name, age and id. But the type of id must be a string and a number at once, so it becomes string & number, which is never. No value can be both.

const c: C = { id: 1, name: 'Neo', age: 30 };
// Error: Type 'number' is not assignable to type 'never'

const d: C = { id: 'x', name: 'Neo', age: 30 };
// Error: Type 'string' is not assignable to type 'never'

There is no error where you wrote A & B, only later, when you try to create or use a value. In the type itself, the problem is hidden. This is the biggest trap of intersections.

If the types of the shared property are compatible, it works as you would expect, and TypeScript uses the narrower one:

type A = { id: string };
type B = { id: 'player-1' | 'player-2' };

type C = A & B;
// id is string & ('player-1' | 'player-2'), which is 'player-1' | 'player-2'

There is a special case. If the conflicting property is a literal type (a fixed value like 'circle'), TypeScript sees that the whole object is impossible and turns the entire type into never:

type X = { kind: 'circle' } & { kind: 'square' };
// X is never

If you build object types with & and a property looks like it has the wrong type, check whether two parts of the intersection disagree about it.

Confusing case 2: primitives and unions of literals

Intersections of simple types behave like the overlap of two sets.

type A = string & number;
// never, no value is a string and a number at the same time

type Status1 = 'online' | 'away';
type Status2 = 'away' | 'offline';

type Either = Status1 | Status2;
// 'online' | 'away' | 'offline'

type Both = Status1 & Status2;
// 'away', only the common member is left

When you intersect two unions of literals, you get only the members they share. If they share nothing, the result is never:

type Nothing = 'online' & 'offline';
// never

Confusing case 3: unions and intersections of functions

This case looks backwards even to experienced developers. Take a union of two functions:

type Print = ((value: string) => void) | ((value: number) => void);

declare const print: Print;

print('Neo');
// Error: Argument of type 'string' is not assignable to parameter of type 'never'

print(42);
// Error: Argument of type 'number' is not assignable to parameter of type 'never'

Why can you not call it with a string? Because TypeScript does not know which function you really have. It could be the one that accepts only strings, or the one that accepts only numbers. A call is safe only if the argument works for both, so the parameter type is the intersection of the two: string & number, which is never.

So a union of functions has an intersection of parameters. A union on the outside becomes an intersection on the inside.

Now the opposite. An intersection of two functions is just a function with overloads, so both ways of calling it work:

type Convert = ((value: string) => number) & ((value: number) => string);

declare const convert: Convert;

const a = convert('42'); // number
const b = convert(42);   // string

If you want a function that accepts a string or a number, you do not need a union of functions. You need a union of parameters:

type Print = (value: string | number) => void;

declare const print: Print;

print('Neo'); // OK
print(42);    // OK

The rule of thumb is: put the union inside the parameter, not around the whole function.

Combining both: (A | B) & C

You can mix unions and intersections in one type. TypeScript treats & like multiplication and | like addition, so it distributes the intersection over the union:

(A | B) & C   is the same as   (A & C) | (B & C)

A practical example is a response that is either a success or an error, and both parts have common fields:

type Success = { success: true; player: { nickname: string } };
type Failure = { success: false; error: string };

type WithMeta = { requestId: string; time: number };

type ApiResult = (Success | Failure) & WithMeta;
// (Success & WithMeta) | (Failure & WithMeta)

function handle(result: ApiResult) {
    console.log(result.requestId); // OK, every member has it

    if (result.success) {
        console.log(result.player.nickname); // narrowed to Success & WithMeta
    } else {
        console.log(result.error);           // narrowed to Failure & WithMeta
    }
}

The discriminated union (success: true or success: false) still works for narrowing, even after the intersection. This is a clean way to add shared fields to every member of a union without repeating them.

Quick comparison

Union A | B Intersection A & B
Meaning A or B (or both) A and B at once
Possible values More (all of A plus all of B) Fewer (only the overlap)
Usable properties of objects Only the shared ones, until you narrow Properties of both
Missing property in an object Allowed if it fits one member Error, all parts are required
Same property, different types Type of the property is a union Type of the property is an intersection (often never)
Primitives, for example string and number string | number never
Unions of literals Joins all members Keeps only shared members
Functions Parameters become an intersection Works like overloads
Typical use Different shapes, optional variants, null Combining types, adding fields

Summary

A union A | B means "A or B": it has more possible values, but you can safely use only what both types share until you narrow it. An intersection A & B means "A and B at once": it has fewer possible values, but you can use the properties of both. Watch out for the confusing cases: a shared property with different types becomes never, intersections of unions keep only the common members, and a union of functions needs an argument that fits all of them. If you are not sure what a type really is, hover over it in your editor, or write it out with a small type alias and check the result.

About the author

  • Front-end developer who pays special attention to the aesthetics and functionality of websites. I love playing with interesting design solutions, creating interfaces that not only work efficiently, but also attract attention with their unique design. I like to derive pleasure from it, like with my old 'Portfolio' website. After hours, I return to classic games or good movies that stimulate the imagination.

No comments yet. Be the first to comment.