On this page
  1. Structural Typing & Narrowing
  2. Contents
  3. Structural Subtyping (Shape Over Name)
  4. Control-Flow Narrowing & Exhaustiveness

Structural Typing & Narrowing

Prev: type_system | Up: type_system | Next: Generics, Constraints & Variance
Rel: Type Systems, unknown, never, is
Ref: TypeScript Handbook — Narrowing
Tags: #public #web #typescript #type-system


Contents


Structural Subtyping (Shape Over Name)

TypeScript checks compatibility by shape, not by declared type name. Any value having at least the required properties satisfies an interface or type alias (except excess property checks on fresh object literals):

interface Point { x: number; y: number }

function dist(p: Point): number {
  return Math.hypot(p.x, p.y);
}

const pt3d = { x: 3, y: 4, z: 5 };
dist(pt3d); // Valid: pt3d structurally contains x and y

Control-Flow Narrowing & Exhaustiveness

TypeScript refines union types automatically along branches using typeof, instanceof, in, truthiness, equality (===), and user-defined type predicates (x is T). Pair a discriminated union with never to catch unhandled cases at compile time:

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rect"; width: number; height: number };

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

Linked from

Related notes