Sub topic 1
Structural vs nominal typing
Prerequisites
This chapter assumes you can:
- Write type annotations and declare interfaces and type aliases in TypeScript.
- Read basic JavaScript objects, classes and functions.
- Run a TypeScript file with
tscor a playground and read the error messages it prints.
You don't need to know generics, variance or compiler options yet. Later chapters cover them. This chapter sets up the one rule the rest of the tutorial builds on.
The question every type system answers
A type checker has to decide one thing over and over: can this value be used where that type is expected? There are two common ways to decide.
- Nominal typing compares names. A value fits a type only if it was declared as that type or as something explicitly derived from it. Java, C# and Rust (for structs) work this way.
- Structural typing compares shapes. A value fits a type if it has all the members the type requires, with compatible types. The names of the declarations don't matter. TypeScript works this way.
The word shape here means the set of members (properties and methods) and their types. In TypeScript, if a type requires x: number and y: number, any value that has those two properties is acceptable.
TypeScript compares shapes
The following program compiles without errors, even though neither value is declared as a Point.
interface Point {
x: number;
y: number;
}
function logPoint(p: Point) {
console.log(`${p.x}, ${p.y}`);
}
const p3 = { x: 1, y: 2, z: 3 };
logPoint(p3); // OK: p3 has at least x and y
class Vec {
constructor(public x: number, public y: number) {}
}
logPoint(new Vec(1, 2)); // OK: Vec never declares that it implements PointTwo things happen here:
p3is an object literal assigned to a variable. Its inferred type is{ x: number; y: number; z: number }. That type has everythingPointrequires, plus an extra property,z. Extra members don't prevent a match.Vecis a class that has never heard ofPoint. It has publicxandyof typenumber, so its instances fit.
In a nominal language, the second call would need class Vec implements Point (and even then the check would be by name). In TypeScript, implements is optional. It only asks the compiler to verify that the class has the right shape at the point where you wrote it.
What a mismatch looks like
A value fails the check when a required member is missing or has an incompatible type. The compiler reports which member is the problem.
interface Point {
x: number;
y: number;
}
function logPoint(p: Point) {
console.log(`${p.x}, ${p.y}`);
}
const onlyX = { x: 1 };
logPoint(onlyX);
// Error: Argument of type '{ x: number; }' is not assignable to parameter
// of type 'Point'. Property 'y' is missing in type '{ x: number; }'
// but required in type 'Point'.
const wrongType = { x: 1, y: "2" };
logPoint(wrongType);
// Error: Type 'string' is not assignable to type 'number'.The rule is directional. The source needs to have at least what the target requires. More is fine, less is not. The next chapter makes this precise as assignability.
Why TypeScript chose structure
The choice follows from the language's goal: describe the JavaScript people already write. JavaScript programmers rarely build class hierarchies just to pass an object to a function. They create object literals, receive JSON, pass options bags and use objects from libraries that know nothing about each other. A name-based system would force wrapper classes or explicit declarations for all of that.
Structural typing gives you several practical benefits:
- Plain objects work. Anything with the right members is accepted, including JSON that you've parsed and validated.
- Libraries stay decoupled. Library A can define an interface and library B can return a matching object without importing A.
- Tests are easier. You can pass a small stub object that has only the members the function uses.
- Refactoring is cheaper. Renaming or moving an interface doesn't break values that merely have the right shape.
interface Logger {
log(message: string): void;
}
function run(logger: Logger) {
logger.log("started");
}
// A test double: no class, no `implements`
const calls: string[] = [];
run({ log: (m) => calls.push(m) });
console.log(calls); // ["started"]Structural typing is not runtime duck typing
You may have heard the phrase "if it walks like a duck and quacks like a duck, it's a duck." JavaScript does this at runtime: a function calls p.x and either the property is there or it isn't. TypeScript's structural typing is a compile-time version of the same idea. It checks, before the program runs, that the properties you use will be there.
This difference matters because types are erased. After compilation, the interface Point does not exist, and nothing in the emitted JavaScript checks shapes. Operations that inspect the runtime class remain nominal in behaviour:
class Vec {
constructor(public x: number, public y: number) {}
}
const v = { x: 1, y: 2 };
const asVec: Vec = v; // OK for the type checker: same shape
console.log(v instanceof Vec); // false: instanceof checks the prototype chain
console.log(asVec instanceof Vec); // false: the annotation changed nothing at runtimeThe assignment compiles because Vec has only public x and y, which v also has. But instanceof looks at the prototype chain, which depends on how the object was built. The type annotation : Vec makes a promise to the compiler. It does not convert the object.
The cost: same shape, different meaning
Structural typing can't tell apart two types that have the same members but mean different things. A name that signals intent has no effect on the check.
interface Celsius {
degrees: number;
}
interface Fahrenheit {
degrees: number;
}
function isBoiling(t: Celsius): boolean {
return t.degrees >= 100;
}
const room: Fahrenheit = { degrees: 212 };
console.log(isBoiling(room)); // compiles and prints true, but the units are wrongA nominal system would reject the call. TypeScript accepts it because both interfaces are { degrees: number }. The same problem appears with user IDs and order IDs that are both strings, or with prices in different currencies that are both numbers.
TypeScript gives you ways to recover the safety when you need it:
- Private and protected members make classes compare by declaration, so they behave nominally. See the chapter "Classes and private members".
- Branded types add a phantom property to make two otherwise identical types differ. See the chapter "Branded types for nominal-style safety".
Neither is the default. You opt in when a mix-up would be costly.
Side-by-side comparison
| Question | Nominal typing | Structural typing (TypeScript) |
|---|---|---|
| What decides compatibility? | The declared name and its declared relationships | The members and their types |
| Is `implements` or `extends` required for a fit? | Yes | No, it only adds a check at the declaration |
| Can unrelated libraries' types interoperate? | Only through shared declarations or adapters | Yes, if shapes match |
| Can two types with the same members be confused? | No | Yes |
| Is the check visible at runtime? | Often, through the runtime type | No, types are erased |
How the checker decides
Conceptually, the compiler asks one question for each position where a value flows into a type: does the source type contain every member the target type requires, with each member's type compatible? The check recurses into nested objects. The following diagram shows the decision for a single object member comparison.
Notice what the diagram doesn't contain: a step that looks at the names of the two types. Names appear in error messages and in your editor, but they don't take part in the decision.
Common mistakes at this stage
- Expecting a name to protect you. Declaring
interface UserId { value: string }andinterface OrderId { value: string }does not make them distinct. They are interchangeable. - Assuming
implementsis what makes a class fit. It is only a verification. Removing it never changes whether instances are accepted, as long as the shape stays the same. - Treating annotations as conversions. Annotating a value with a class type doesn't give it that class's prototype or methods.
- Expecting extra properties to always be rejected. A variable with extra properties is accepted. Object literals written directly at the call site get an additional check that you'll meet in a later chapter.
- Relying on a type to describe the exact keys at runtime. A value typed as
Pointmay carry more properties thanPointlists. The last chapter returns to this.
Where this leads
The rest of the tutorial applies this single rule to more kinds of types. The next chapter defines assignability precisely. After that come object shapes and extra properties, then the extra checks and the exceptions: optional and readonly members, functions, classes, generics and branding.
Exercise
Given interface Meters { value: number } and interface Feet { value: number }, a function function walk(distance: Meters) {}, and a variable const f: Feet = { value: 10 };, does walk(f) compile? Explain why, and name one way to make TypeScript reject the call.
Show answer
It compiles. TypeScript compares the shapes, and both interfaces are { value: number }, so a Feet value is assignable to Meters. The names Meters and Feet play no part in the check. To make the compiler reject it, give the types different shapes, for example with branded types that add a phantom property such as __brand: "Meters" and __brand: "Feet", so a Feet value no longer has the member that Meters requires.
Exercise
A class Vec has public x: number and y: number. A plain object { x: 1, y: 2 } is assigned to a variable annotated Vec. Does it compile, and what does v instanceof Vec return at runtime for that object?
Show answer
It compiles, because the object has every member Vec requires. v instanceof Vec returns false, because instanceof checks the prototype chain and the object was created as a plain object, not by new Vec(...). The type annotation does not change the value at runtime.