TypeScript - Literal, Union & Intersection Types

Literal Types

type Direction = "left" | "right" | "up" | "down";

Union Types

function padLeft(value: string, padding: number | string) {
  if (typeof padding === 'number') return ' '.repeat(padding) + value;
  return padding + value;
}

Intersection Types

type WithId = { id: string };
type Timestamped = { createdAt: Date };

type Entity = WithId & Timestamped; // has both

Discriminated unions

type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; size: number };

type Shape = Circle | Square;

function area(s: Shape) {
  switch (s.kind) {
    case "circle": return Math.PI * s.radius ** 2;
    case "square": return s.size ** 2;
    default: const _exhaustive: never = s; return _exhaustive;
  }
}