Basic · 12 of 13 · 12 min read
Structural typing
Compatibility decided by shape rather than by name — what that buys you, where the compiler makes an exception, and how to fake a nominal type.
- Structural typing
TypeScript decides whether two types are compatible by looking at their shape, not at the name they were declared with. Two independently declared identical interfaces are interchangeable, and a plain object can satisfy a class type.
Names do not matter
interface Point { x: number; y: number }
interface Coord { x: number; y: number }
const p: Point = { x: 1, y: 2 };
const c: Coord = p; // fine — the shapes are identical
function draw(point: Point) { return point.x + point.y; }
class Pixel {
constructor(public x: number, public y: number) {}
}
console.log(draw(new Pixel(1, 2))); // 3 — Pixel never mentions Point
console.log(draw({ x: 1, y: 2 })); // 3
console.log(c.x);
Coming from a nominal language this looks unsafe and is mostly the opposite: it means a function can accept anything that works, without the caller having to declare an intention.
More is fine, less is not
interface Point { x: number; y: number }
const extra = { x: 1, y: 2, colour: "red" };
const point: Point = extra; // fine — it has everything Point needs
// const missing: Point = { x: 1 }; // Property 'y' is missing
console.log(point.x);
A value with extra properties is assignable. That is what makes a User usable wherever
{ name: string } is expected — the Interface Segregation principle, for free.
interface User { id: number; name: string; email: string }
function greet(person: { name: string }) { return `Hi ${person.name}`; }
const user: User = { id: 1, name: "Ana", email: "a@b.c" };
console.log(greet(user)); // a full User fits
console.log(greet({ name: "Beto" })); // and so does the minimum
Exception one: object literals
interface Options { timeout: number }
const fromVariable = { timeout: 1, retries: 3 };
const a: Options = fromVariable; // fine
// const b: Options = { timeout: 1, retries: 3 };
// Object literal may only specify known properties
A fresh object literal gets an excess property check on top of the structural rule, because an
undeclared property written inline is almost always a typo rather than a deliberate extra. Going
through a variable is the documented way round it — and satisfies is the way that still checks:
interface Options { timeout: number }
const checked = { timeout: 1 } satisfies Options;
// const typo = { timeuot: 1 } satisfies Options; // caught
console.log(checked.timeout);
Exception two: private members
A private or # member makes a class nominal. Two classes with identical shapes are no
longer interchangeable if either has one:
class Open { constructor(public name: string) {} }
const a: Open = { name: "Ana" }; // a plain object is fine
class Secretive {
private token = "x";
constructor(public name: string) {}
}
// const b: Secretive = { name: "Ana", token: "x" };
// Types have separate declarations of a private property 'token'
const c: Secretive = new Secretive("Ana"); // only a real one will do
console.log(a.name, c.name);
Two different classes each declaring private token are also incompatible, even though the
shapes match — the private member is identified by its declaration, not its name.
Functions compare structurally too
type Handler = (value: string, index: number) => void;
const ignoresIndex: Handler = (value) => console.log(value); // fewer params: fine
// const wantsMore: Handler = (v, i, extra: boolean) => {}; // more: rejected
["a"].forEach((value) => console.log(value)); // the everyday consequence
ignoresIndex("a", 0);
Fewer parameters is assignable because the extra arguments can simply be ignored. More is not,
because they would arrive as undefined.
| Compared | Rule |
|---|---|
| Object properties | the target’s members must all be present and compatible |
| Object literals | plus an excess property check |
Classes with private / # |
nominal — same declaration or nothing |
| Function parameters | fewer is assignable; parameter types are checked contravariantly |
| Function returns | checked covariantly — narrower is assignable |
| Arrays | covariant, and deliberately unsound |
Faking a nominal type
Structural typing means type UserId = string is just string, so nothing stops a PostId being
passed:
type UserId = string;
type PostId = string;
function loadUser(id: UserId) { return id; }
const postId: PostId = "p_1";
console.log(loadUser(postId)); // no error — both are string
A brand makes them structurally different by intersecting a phantom property nothing can produce by accident:
type UserId = string & { readonly __brand: "UserId" };
type PostId = string & { readonly __brand: "PostId" };
const asUserId = (value: string) => value as UserId;
function loadUser(id: UserId) { return id; }
const user = asUserId("u_1");
console.log(loadUser(user)); // "u_1"
// loadUser("u_1" as PostId); // 'PostId' is not assignable to 'UserId'
// loadUser("u_1"); // a plain string is not assignable either
The cost is the cast at the boundary, so it is worth it for identifiers that get mixed up in practice and overkill for everything else.
Weak types
A type whose members are all optional is almost universally assignable, which TypeScript special-cases:
interface Options { timeout?: number; retries?: number }
// const a: Options = { nothing: true };
// Type has no properties in common with type 'Options'
const b: Options = {}; // fine — empty is legal
console.log(Object.keys(b).length);
The weak-type check requires at least one property in common, which catches the obvious mistakes. A required discriminant removes the ambiguity entirely:
interface Safer { kind: "options"; timeout?: number }
const c: Safer = { kind: "options" };
console.log(c.kind);
Common mistakes
Expecting a class to be nominal
Mistake. Assuming only new Person(...) can satisfy a Person parameter.
Why it fails. Without a private member the class is just its instance shape, so any
compatible object works.
What to do instead. Nothing, usually — it is what makes testing with plain objects pleasant.
Add a private brand field when the distinction genuinely matters.
Thinking an alias creates a new type
Mistake. type Email = string to stop arbitrary strings being passed.
Why it fails. An alias is a synonym; the compiler sees string.
What to do instead. A branded type, or a validated wrapper if you need runtime checking too.
Working around the excess property check with as
Mistake. const options = { timeuot: 1 } as Options.
Why it fails. The assertion turns off the one check that was going to catch the typo.
What to do instead. Fix the property, declare it, or use satisfies.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
TypeScript compares types by their shape, not by the name they were declared with.
Does this compile?
interface Point { x: number; y: number }
interface Coord { x: number; y: number }
const p: Point = { x: 1, y: 2 };
const c: Coord = p;Two type aliases both say string. Can you stop one being passed where the other is expected?
A function with fewer parameters is assignable where one with more is expected.
Does this compile?
type Handler = (value: string, index: number) => void;
const handler: Handler = (value) => console.log(value);Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.