Skip to content

Structural typing: shapes, not names

Working knowledgeConcept

TypeScript accepts a Pixel where you asked for a Point, and a UserId where you asked for an OrderId, even though the names differ. It compares shapes, not names. Here is how that check works, where it surprises people, and how to get names back when you need them.

01 Two names, one type

Neither of these is an error. Vec never mentions Point, and OrderId is meant to be a different thing from UserId.

ids.ts
interface Point { x: number; y: number }
class Vec {
constructor(public x: number, public y: number) {}
}
const p: Point = new Vec(1, 2); // OK
type UserId = string;
type OrderId = string;
function cancel(id: OrderId) {}
const user: UserId = "u_1";
cancel(user); // OK, sadly

A type alias is only a second name for the same type, so UserId and OrderId are both just string. And a Vec has an x: number and a y: number, which is everything a Point needs.

02 Names versus shapes

Nominal (Java, C#)Same declared nameA Vec is a Point only if its class says implements Point or extends it. Matching fields are not enough.
Structural (TypeScript)Same shapeA value fits a type when it has every property the type requires, with compatible types. The name and the declaration do not matter.

TypeScript was built to describe existing JavaScript, where objects are often plain literals with no class at all. Checking by shape lets it type that code without asking you to declare relationships up front. It also fits erasure: at runtime there are no interface names left to compare.

03 How the checker compares two types

TypeScript
interface Point { x: number; y: number }
interface Pixel { x: number; y: number; colour: string }
const px: Pixel = { x: 1, y: 2, colour: "red" };
const p: Point = px;

To decide whether Pixel is assignable to Point, the checker walks the properties of the target, Point, one by one, and looks each up on the source. Nested objects are compared the same way, property by property, all the way down.

Assigning a Pixel to a Point
Step 1 of 5
Source Pixel
Is Pixel assignable to Point?
Point needsPixel hasVerdict
xnumbernumber
ynumbernumber
colour—string
  • property being checked
  • looked up on Pixel
  • verdict just made
  • passes
  • not checked yet

The checker meets const p: Point = px;. It does not compare the names Pixel and Point. It lists what Point needs, and what px has.

Point target

The check fails as soon as one property is missing or has a type that does not fit. The error message reports that path:

Text
error TS2322: Type '{ x: number; y: string; }' is not assignable to type 'Point'.
Types of property 'y' are incompatible.
Type 'string' is not assignable to type 'number'.

04 The exception: fresh object literals

Extra properties are fine, with one exception. When you write an object literal straight into a typed slot, an extra property is almost certainly a typo, so TypeScript runs an excess property check on it. The same object passed through a variable is not checked.

Literal: error
const q: Point = { x: 1, y: 2, colour: "red" };
// error TS2353: Object literal may only specify known
// properties, and 'colour' does not exist in type 'Point'.
Via a variable: OK
const px = { x: 1, y: 2, colour: "red" };
const q: Point = px;
// OK: px is not a fresh literal, so the
// normal shape rules apply.

A related rule catches types where every property is optional, such as an options object. Assigning something that shares none of its properties is an error (has no properties in common with type), even though, strictly by shape, nothing required is missing.

05 When you want names back: brands

To stop a UserId going where an OrderId belongs, give each a property the other cannot have. The property exists only in the type: no value ever carries it, so you create one with a cast in a single trusted place.

ids.ts
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
const asOrderId = (s: string) => s as OrderId; // the one trusted place
function cancel(id: OrderId) {}
const user = "u_1" as UserId;
cancel(user); // error
Text
error TS2345: Argument of type 'UserId' is not assignable to parameter of type 'OrderId'.
Type 'UserId' is not assignable to type '{ readonly __brand: "OrderId"; }'.
Types of property '__brand' are incompatible.
Type '"UserId"' is not assignable to type '"OrderId"'.

This is still structural typing: the shapes now differ in __brand, so they no longer match. Classes give you something similar for free: if a class has a private or protected member, only instances of that class (or its subclasses) are assignable to it, because the checker requires the private member to come from the same declaration.

06 Where shapes surprise you

const e: {} = 5;The empty type accepts almost anything{} requires no properties, so every value except null and undefined fits, numbers and strings included. Use object for "any non-primitive" or unknown for "anything".
[1, 2, 3].forEach(() => count++);Fewer parameters are fineA function that takes fewer parameters is assignable to one that takes more, because ignoring extra arguments is safe in JavaScript. This is why callbacks can skip index and array.
type H = { on(e: string | number): void }; const h: H = { on(e: string) {} };Method parameters are checked looselyUnder strict, function-typed properties check parameters properly, but method syntax is still bivariant, so this compiles and h.on(5) reaches code that expects a string. Write on: (e: string | number) => void to get the strict check.
if (shape instanceof Point)Assuming a shape means a classA value can fit a type without being built by any class, so instanceof tells you nothing about structural types. Check the properties instead.

07 Check yourself

Question

interface Named { name: string }. A class Dog has name: string and bark(): void, and does not mention Named. Is const n: Named = new Dog(); allowed?

Question

With type Celsius = number and type Fahrenheit = number, what does const f: Fahrenheit = c do when c is a Celsius?

Question

Which line is an error with interface Point { x: number; y: number }?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?