TExcelTAD
Home › TypeScript › TS Structural Typing

TypeScript Structural Typing

Languages such as Java and C# use nominal typing: a value is a Customer only if it was created from the Customer class (or a class that explicitly extends it). TypeScript works differently. It uses structural typing — sometimes called "duck typing at compile time": if it has the right shape, it is the right type. Names don't matter; only the properties and their types do.

Understanding this one idea explains a lot of TypeScript behaviour that otherwise looks surprising.

Same shape, same type

ts · try it yourself
interface Point {
  x: number;
  y: number;
}

class Pixel {
  constructor(public x: number, public y: number, public color: string) {}
}

function describe(p: Point): string {
  return `(${p.x}, ${p.y})`;
}

const literal = { x: 1, y: 2 };
const pixel = new Pixel(5, 8, "red");

console.log(describe(literal));   // a plain object
console.log(describe(pixel));     // a class instance that never mentions Point
(1, 2)
(5, 8)

Pixel never says implements Point, yet it is accepted, because it has x: number and y: number. Its extra color property doesn't hurt: a type with more properties is assignable to a type that needs fewer. This is called assignment compatibility, and the rule is "the target's requirements must all be satisfied by the source".

Missing properties are errors

The reverse direction fails — a value with fewer properties can't stand in for a type that needs more:

ts · try it yourself
interface Point3D {
  x: number;
  y: number;
  z: number;
}

const flat = { x: 1, y: 2 };
const p: Point3D = flat;
console.log(p);
main.ts(8,7): error TS2741: Property 'z' is missing in type '{ x: number; y: number; }' but required in type 'Point3D'.

Excess property checks on object literals

There is one important exception to "extra properties are fine". When you write an object literal directly where a specific type is expected, TypeScript performs an excess property check. A property that the target doesn't know about is most likely a typo, so it is reported:

ts · try it yourself
interface Options {
  width: number;
  height?: number;
}

const opts: Options = { width: 100, heigth: 50 };
console.log(opts);
main.ts(6,37): error TS2561: Object literal may only specify known properties, but 'heigth' does not exist in type 'Options'. Did you mean to write 'height'?

The check only applies to fresh object literals. If the object is first stored in a variable, the extra property is allowed by the normal structural rule:

ts · try it yourself
interface Options {
  width: number;
  height?: number;
}

const raw = { width: 100, heigth: 50 };
const opts: Options = raw;   // allowed: raw is not a fresh literal
console.log(opts.height);    // the typo silently became "missing"
undefined

Tip: Excess property checks are a safety net for typos in literals. Annotating object literals at the place you create them (instead of later) gets you that safety net.

Functions are compared structurally too

A function type is compatible with another if its parameters and return type line up. A function may also take fewer parameters than the type allows — that is why you can pass (x) => ... to Array.prototype.map, whose callback receives three arguments:

ts · try it yourself
type Handler = (value: number, index: number) => void;

const logValue = (v: number) => console.log("value", v);
const handlers: Handler[] = [logValue, (v, i) => console.log(i, "->", v * 10)];

for (const h of handlers) {
  h(3, 0);
}
value 3
0 -> 30

Classes are structural as well

Two classes with identical public members are interchangeable, even if they're unrelated:

Situation Compatible?
Two classes with the same public properties yes
One class has an extra property the bigger one can be used as the smaller
Either class has a private or #private member only if both come from the same declaration
An object literal with the right shape vs a class type yes (for public members)

The private rule gives you a way to opt into nominal behaviour when you need it.

Simulating nominal types with brands

Structural typing means two aliases of string — say a UserId and an OrderId — are freely mixable, which can hide bugs. A common pattern is a brand: an extra phantom property that exists only in the type system.

ts · try it yourself
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };

const toUserId = (s: string) => s as UserId;
const toOrderId = (s: string) => s as OrderId;

function loadUser(id: UserId): string {
  return `user ${id}`;
}

const u = toUserId("u-17");
const o = toOrderId("o-99");
console.log(loadUser(u));
console.log(loadUser(o));
main.ts(14,22): error TS2345: Argument of type 'OrderId' is not assignable to parameter of type 'UserId'.
  Type 'OrderId' is not assignable to type '{ readonly __brand: "UserId"; }'.
    Types of property '__brand' are incompatible.
      Type '"OrderId"' is not assignable to type '"UserId"'.

At runtime both IDs are just strings — the brand costs nothing — but the compiler now refuses to mix them up. Remove the last line and the program runs.

Test yourself

Can an object { x: 1, y: 2, z: 3 } stored in a variable be passed where { x: number; y: number } is expected?

  1. No, extra properties are never allowed
  2. Yes, extra properties are fine for non-literal values
  3. Only if it is a class instance
  4. Only with as any

When does TypeScript report an "Object literal may only specify known properties" error?

  1. Whenever a type has extra properties
  2. When a fresh object literal has a property the target type doesn't declare
  3. Only for classes
  4. Only with noImplicitAny off

What is a "branded" type used for?

  1. Adding runtime validation
  2. Making structurally identical types incompatible
  3. Exporting types from a module
  4. Speeding up compilation