All academies
Roadmap/Advanced

Level 12

Advanced Types

Unions, intersections, conditional types, mapped types, and template literal types turn TypeScript's type system into a small functional language for computing types from other types.

30 min read + quiz

Unions and Narrowing

A union type A | B means a value is one of several possibilities, and the compiler forces you to figure out which before using type-specific members. This is TypeScript's answer to the billion-dollar-mistake problem: string | null makes the null case impossible to forget.

The crucial skill is narrowing — using runtime checks that the compiler understands (typeof, equality checks, the in operator) to shrink a union inside a branch. After if (typeof x === 'string'), x is just string in that block.

Prefer modeling states as unions of specific shapes rather than one shape with many optional fields. A type like { status: 'loading' } | { status: 'success'; data: string } makes illegal states (success with no data) unrepresentable, which eliminates whole categories of bugs before they are written.

type LoadState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: string[] }
  | { status: "error"; message: string };

function render(state: LoadState): string {
  switch (state.status) {
    case "idle":
      return "Waiting...";
    case "loading":
      return "Spinner";
    case "success":
      return state.data.join(", "); // data exists ONLY here
    case "error":
      return "Oops: " + state.message;
  }
}

Each branch sees only the fields that exist in that state.

Intersections: Composing Capabilities

An intersection A & B produces a type with the members of both. Where unions say 'one of these', intersections say 'all of these at once'. They are the type-level equivalent of mixing capabilities together.

Intersections are most useful for composing small, focused shapes: Timestamps & Identified & UserFields. Each piece can be reused across many entities, and changes to shared fields happen in one place.

Beware of impossible intersections. string & number has no possible value and collapses to never, and intersecting two object types with a conflicting property (name: string in one, name: number in the other) makes that property never. When a value mysteriously refuses every assignment, check for a hidden never in an intersection.

interface Identified {
  id: string;
}
interface Timestamps {
  createdAt: Date;
  updatedAt: Date;
}

type UserRecord = Identified &
  Timestamps & {
    email: string;
  };

const u: UserRecord = {
  id: "u_1",
  email: "ada@example.com",
  createdAt: new Date(),
  updatedAt: new Date(),
};

type Impossible = string & number; // never — no value can satisfy both

Intersections merge members; conflicting primitives collapse to never.

Conditional Types

A conditional type, T extends U ? X : Y, is an if-expression that runs during type checking. It lets a type depend on another type, which is essential for library authors and occasionally invaluable in application code.

The real power comes from infer, which pattern-matches inside a type and captures part of it. ReturnType<T> is defined as T extends (...args: never[]) => infer R ? R : never — it literally destructures the function type and extracts R.

One behavior that surprises everyone: conditional types distribute over unions when checked against a bare type parameter. ToArray<string | number> becomes string[] | number[], not (string | number)[]. Wrap both sides in tuples — [T] extends [U] — when you want to treat the union as a single unit.

type ToArray<T> = T extends unknown ? T[] : never;
type A = ToArray<string | number>; // string[] | number[] (distributed!)

type NoDistribute<T> = [T] extends [unknown] ? T[] : never;
type B = NoDistribute<string | number>; // (string | number)[]

type ElementOf<T> = T extends readonly (infer E)[] ? E : never;
type C = ElementOf<Array<{ id: number }>>; // { id: number }

type UnwrapPromise<T> = T extends Promise<infer V> ? V : T;
type D = UnwrapPromise<Promise<string>>; // string
type E = UnwrapPromise<number>;          // number

infer extracts pieces of types; distribution splits unions.

Mapped Types

Mapped types iterate over the keys of a type and produce a new type, like a for-loop over properties. The syntax { [K in keyof T]: ... } is how Partial, Required, and Readonly are implemented in a single line each.

Modifiers can be added or removed during mapping: a plus or minus before ? and readonly toggles optionality and mutability. { [K in keyof T]-?: T[K] } is exactly Required<T> — it strips the optional marker from every property.

Since TypeScript 4.1, the as clause lets you rename keys while mapping. Combined with template literal types, you can compute getter names from property names — this is how libraries generate onXxxChange handler types automatically from a props object.

type Mutable<T> = {
  -readonly [K in keyof T]: T[K];
};

type Getters<T> = {
  [K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};

interface Point {
  readonly x: number;
  readonly y: number;
}

type MutablePoint = Mutable<Point>; // { x: number; y: number }
type PointGetters = Getters<Point>;
// { getX: () => number; getY: () => number }

Mapping transforms every property; 'as' renames keys in flight.

Template Literal Types

Template literal types build string types from other string types. The type `${Direction}-${Size}` computes the cross product of two unions, giving you top-small, top-large, bottom-small, and so on — every combination, checked by the compiler.

They shine at typed string contracts: CSS property patterns, route paths like /users/:id, event names like click or change. Instead of accepting any string and validating at runtime, the type system rejects malformed strings at the call site.

The built-in string manipulation types — Uppercase, Lowercase, Capitalize, Uncapitalize — work inside template literal types, which is what makes key-renaming mapped types practical. Keep these types for genuinely finite string spaces; typing every possible email address is not their job.

type Size = "sm" | "lg";
type Spacing = `m${"t" | "b"}-${Size}`;
// "mt-sm" | "mt-lg" | "mb-sm" | "mb-lg"

type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickHandler = EventName<"click">; // "onClick"

function setSpacing(cls: Spacing): void {
  // Only the four valid class strings are accepted.
}

setSpacing("mt-sm"); // OK
// setSpacing("mt-md"); // Error: not assignable to Spacing

String unions multiply into every valid combination.

Try it yourself

This lesson's example is preloaded in the playground — break it, fix it, extend it.

Open in playground

Check your understanding

Question 1 · Multiple choice

Why is a discriminated union like { status: 'success'; data: string } | { status: 'error'; message: string } better than one interface with optional data and message fields?

Question 2 · Predict the output

Given this distributive conditional type, what is type Result?

type ToArray<T> = T extends unknown ? T[] : never;
type Result = ToArray<string | boolean>;

Question 3 · True or false

The intersection type string & number is a compile error.

Question 4 · Find the error

This mapped type is intended to make all properties optional, but it has a bug. What is it?

type MyPartial<T> = {
  [K in keyof T]-?: T[K];
};

Question 5 · Multiple choice

What does the template literal type `on${Capitalize<'click' | 'focus'>}` evaluate to?