On this page
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
- tuts/typescript/builtins/any
- tuts/typescript/builtins/as_const
- tuts/typescript/builtins/asserts
- tuts/typescript/builtins/enum
- tuts/typescript/builtins/infer
- tuts/typescript/builtins/is
- tuts/typescript/builtins/keyof
- tuts/typescript/builtins/namespace
- tuts/typescript/builtins/never
- tuts/typescript/builtins/readonly
- tuts/typescript/builtins/satisfies
- tuts/typescript/builtins/typeof
- tuts/typescript/builtins/unknown
- tuts/typescript/builtins/void
- tuts/typescript/tutorials/discriminated_unions_and_state_machines
- tuts/typescript/type_system
- tuts/typescript/type_system/generics_and_constraints
- tuts/typescript/type_system/structural_typing_and_narrowing
Related notes
- tuts/typescript/builtins/is Linked here; links to this page; shared tags: #typescript, #web
- tuts/typescript/builtins/never Linked here; links to this page; shared tags: #typescript, #web
- tuts/typescript/builtins/unknown Linked here; links to this page; shared tags: #typescript, #web
- tuts/typescript/type_system Linked here; links to this page; shared tags: #typescript, #web
- tuts/typescript/type_system/generics_and_constraints Linked here; links to this page; shared tags: #typescript, #web
- tuts/typescript/builtins/any links to this page; shared tags: #typescript, #web
- tuts/typescript/builtins/as_const links to this page; shared tags: #typescript, #web
- tuts/typescript/builtins/asserts links to this page; shared tags: #typescript, #web
- tuts/typescript/builtins/enum links to this page; shared tags: #typescript, #web
- tuts/typescript/builtins/infer links to this page; shared tags: #typescript, #web