Lesson 12 +10 XP

Intersection Types & Literal Types

Intersection Types & Literal Types

TypeScript provides operators to combine types and lock variables down to exact value literals.

Intersection Types (&)

An intersection type combines multiple types into one. An object must satisfy ALL combined types.

type Loggable = { log: (msg: string) => void };
type Serializable = { serialize: () => string };

type Service = Loggable & Serializable;

const myService: Service = {
  log: (msg) => console.log(msg),
  serialize: () => "json_data"
};

Literal Types

Literal types lock a value to exact strings, numbers, or booleans.

type Direction = "North" | "South" | "East" | "West";
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;

let move: Direction = "North";
// move = "Up"; // Error: Type '"Up"' is not assignable to type 'Direction'.

Discriminated Unions

Combining literal types with object unions creates powerful Discriminated Unions:

type NetworkState =
  | { status: "loading" }
  | { status: "success"; data: string }
  | { status: "error"; error: Error };

TL;DR

  • Intersection (&) merges multiple type requirements into a single combined type.
  • Literal types restrict values to exact specific literal values.