iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

TS Intersection Types

An intersection type combines several types into one: A & B. The result has every property from every type — the opposite of a union.

Basics

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

const p: Person = { name: 'Ada', age: 36 };

Mixing existing types

TS
type Logger = { log(msg: string): void };
type Timer  = { now(): number };

function setup(deps: Logger & Timer) {
    deps.log('starting at ' + deps.now());
}

Intersection of unions

TS
type AB = 'a' | 'b';
type BC = 'b' | 'c';

type Both = AB & BC;   // 'b' — only common members

When properties collide

If two types declare the same property with incompatible types, the intersection is never:

TS
type A = { x: number };
type B = { x: string };
type C = A & B;        // x: number & string  → effectively never

vs interface extension

TS
// interfaces
interface Named { name: string }
interface Aged  { age: number }
interface Person extends Named, Aged {}

// type aliases
type Person2 = Named & Aged;

Pick whichever fits your style. Interfaces have nicer error messages; type aliases compose more flexibly.

Tip: Intersection is "AND" — every property required. Union is "OR" — value matches any one. Remember the algebra: {a: 1, b: 2}: A & B; 1 | 'one' = number | string.

Example

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

const p: Person = { name: 'Ada', age: 36 };
console.log(p);
Try it Yourself »

Exercise

Operator that intersects types.

type Person = Named Aged;

Test yourself

Q1. A & B has every property of…
Q2. When two types in A & B disagree on a property type…
Q3. Intersection of unions yields…

Discussion

Loading…