Sub topic 3
Structural typing: shape, not name
This chapter assumes you can read TypeScript type annotations, interfaces and type aliases. It also assumes you have seen basic compiler errors such as "Type 'X' is not assignable to type 'Y'". The earlier chapters introduced types as sets of values and assignability as a relation between a source type and a target type. This chapter covers how TypeScript decides that relation for object types.
The rule: compare shapes
TypeScript uses structural typing. A source type is assignable to a target type when the source has every member the target requires, and each of those members has a compatible type. The names of the types, the place they were declared, and any implements or extends relationship play no part in that decision.
This differs from nominal typing, used by Java and C#, where a Dog is an Animal only if the declaration says so. In TypeScript, a type is a Point for assignment purposes if it has the shape of a Point.
interface Point {
x: number;
y: number;
}
interface Coordinate {
x: number;
y: number;
}
class Vec {
constructor(public x: number, public y: number) {}
length(): number {
return Math.hypot(this.x, this.y);
}
}
function distance(p: Point): number {
return Math.hypot(p.x, p.y);
}
const c: Coordinate = { x: 3, y: 4 };
console.log(distance(c)); // 5: Coordinate and Point have the same shape
console.log(distance(new Vec(3, 4))); // 5: Vec has x and y, plus an extra methodCoordinate never mentions Point, and Vec never says it implements anything. Both calls compile because each source has x: number and y: number.
Extra members are fine
The check runs from the target's point of view. The target lists what it needs, and the compiler looks each item up in the source. Members the target does not mention are ignored.
interface Point {
x: number;
y: number;
}
const point3d = { x: 1, y: 2, z: 3 };
const a: Point = point3d; // OK: point3d has every property Point requires
const b: Point = { x: 1, y: 2, z: 3 }; // Error: 'z' does not exist in type 'Point'This ties back to types as sets. Point is the set of all values with numeric x and y. A type that adds z describes a smaller set, because fewer values satisfy more requirements. Every value in the smaller set is also in the larger one, so the assignment is safe. Adding properties makes a type more specific, and a more specific type can stand in for a less specific one.
The second assignment fails for a different reason. A fresh object literal written directly at the assignment gets an extra check for unknown properties. That check is the subject of a later chapter. The structural rule itself allows z, as the first assignment shows.
What the compiler checks, step by step
For each property in the target, the compiler does the following:
- It looks for a property with the same name in the source.
- If the property is missing, the assignment fails, unless the target marks it optional.
- If the property is present, the compiler checks that the source property's type is assignable to the target property's type.
Step 3 is a recursive application of the same relation. The nesting can go as deep as the types do.
Here is the recursion on nested objects:
interface Named {
name: string;
}
interface Employee {
person: Named;
id: number;
}
const staff = {
person: { name: "Ada", title: "Engineer" },
id: 7,
};
const e: Employee = staff; // OK: staff.person has name: string, extra title is ignored
const broken = { person: { title: "Engineer" }, id: 8 };
const f: Employee = broken;
// Error: Property 'name' is missing in type '{ title: string; }'
// but required in type 'Named'.When a nested check fails, the error message names the innermost mismatch. Read it from the bottom up to find the property that actually fails.
Names and declaration style do not matter
Several things that look like they should create a distinction do not:
- Interface versus type alias. An
interfaceand atypealias with the same members are interchangeable. - Class versus interface. A class instance type is compared by its members, so a plain object can satisfy a class type when the class has only public members.
- Declaration site. Two types declared in different files or packages are compatible if their shapes match.
interface Logger {
log(message: string): void;
}
type Sink = { log: (message: string) => void };
class ConsoleLogger {
log(message: string): void {
console.log(message);
}
}
const l1: Logger = new ConsoleLogger(); // OK, no 'implements' needed
const l2: Sink = l1; // OK, interface and alias share a shape
const l3: ConsoleLogger = { log: (m) => console.log(m) }; // OK: only public membersThe last line stops compiling as soon as ConsoleLogger gets a private member. A later chapter on classes covers that exception.
Consequences and gotchas
Structural typing is convenient because you can pass any compatible value without wrapper types or adapter classes. It also means the compiler cannot tell apart types that happen to share a shape.
interface Meters {
value: number;
}
interface Feet {
value: number;
}
function runMarathon(distance: Meters): string {
return `Running ${distance.value} meters`;
}
const lap: Feet = { value: 400 };
console.log(runMarathon(lap)); // compiles, but passes feet where meters are expectedThe compiler accepts this call because Feet and Meters have the same shape. If you need the compiler to reject it, you must add a distinguishing member. The chapter on branded types shows how.
Two further points matter in practice:
- Empty and tiny targets accept almost everything. A parameter of type
{}accepts any value exceptnullandundefined. A target with a single property accepts every type that has that property. - The relation is not symmetric.
Employeeis assignable toNamed-shaped targets, but a plainNamedis not assignable toEmployee. Always identify which type is the source and which is the target before predicting the result.
Exercise
Given interface Pair { first: number; second: number } and const p = { first: 1, second: 2, third: 3 };, does const q: Pair = p; compile? Does const r: Pair = { first: 1, second: 2, third: 3 }; compile? Explain the difference.
Show answer
The first compiles. p has both properties that Pair requires, and the structural check ignores the extra third property. The second does not compile, because a fresh object literal assigned directly to a typed target is also checked for excess properties, and third is not in Pair. The structural rule allows extras, but the literal check is an additional rule.
Exercise
Why does runMarathon(lap) compile in the Meters and Feet example, and what would the compiler need in order to reject it?
Show answer
Both types require a single value: number property, so their shapes are identical and each is assignable to the other. To make the compiler reject the call, the types would need a member that differs between them, such as a distinguishing brand property on each.