Codectionary / Developer documentation / TypeScript

Structural Type Compatibility

TypeScript usually compares object types by their members rather than by a declared type name.

What it is and why to use it

TypeScript usually compares object types by their members rather than by a declared type name. A value can satisfy a smaller interface when it contains the required compatible fields. This structural approach fits JavaScript’s flexible object composition and makes small reusable contracts practical.

Common mistakes and limitations

Fresh object literals receive additional excess-property checking. Private and protected class members also impose compatibility rules beyond a simple public-field comparison. Structural assignment does not strip extra properties or validate untrusted data.

Run this example

Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.

Terminal — compile and run

npx tsc example.ts --strict --target ES2022 --module commonjs
node example.js

Syntax

type Named = { name: string };

Examples

Structural Type Compatibility

Standalone TypeScript 5.8+ example; expected output is explained below.

type Named = { name: string };
function welcome(person: Named): string { return "Hello, " + person.name; }
const learner = { name: "John", score: 87 };
console.log(welcome(learner));
  1. Named requires a name string and does not require a score.
  2. learner already has the compatible required member, so it can be passed to welcome.
  3. The function relies only on the contract it declares. The score remains on the runtime object and is not removed by the assignment.
  4. Expected output: Hello, John

Best practices

  • Fresh object literals receive additional excess-property checking. Private and protected class members also impose compatibility rules beyond a simple public-field comparison. Structural assignment does not strip extra properties or validate untrusted data.
  • Keep external-input validation separate from compile-time type descriptions.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading