Glossary / Structural typing

Structural typing

Structural typing determines compatibility primarily from the members a value has rather than from an explicit declared identity or inheritance relationship. TypeScript uses structural compatibility for most object and function types, which makes JavaScript-shaped data convenient to model but can allow semantically distinct concepts to be mixed accidentally.

Compatibility and excess-property checks

type Point = { x: number; y: number };
const value = { x: 1, y: 2, label: 'origin' };
const point: Point = value; // structurally compatible

A fresh object literal assigned directly to a target can receive an excess-property check, which catches likely typos; this is a contextual diagnostic, not nominal typing. Once stored in a variable, extra members usually do not prevent assignment. Classes with private or protected members have compatibility constraints tied to declaration origin, adding a limited nominal-like rule.

Function parameter and return compatibility includes variance rules, and compiler settings such as strictFunctionTypes affect safety. Structural typing also appears in generic constraints and inferred object shapes.

Tradeoffs and design

Structural typing reduces boilerplate for adapters and plain data. It can confuse IDs, currencies, or domain entities that have identical representations. Use branded/opaque types, discriminants, or wrapper objects when identity matters. Do not infer runtime validation from a structural type: untrusted data still needs checks.

Interview questions

  1. What makes two object types compatible? Generally, the source has members required by the target with compatible types.
  2. What is excess property checking? An extra diagnostic for fresh object literals, not a general exact-object type rule.
  3. Are TypeScript classes nominal? Mostly structurally typed, though private/protected members impose origin-based compatibility constraints.
  4. How distinguish two string IDs? Use brands/opaque wrappers or runtime value objects.
  5. Does structural typing validate JSON? No; it is compile-time analysis only.

References