Sub topic 1
Why TypeScript lets you mix up IDs: structural typing
A function takes an OrderId. You pass it a UserId. The compiler says nothing, and the program loads the wrong record or fails at runtime. This is not a bug in the compiler. It follows from how TypeScript decides whether one type fits another. This chapter explains that rule, shows where it causes ID mix-ups, and sets up the problem that branded types solve in the later chapters.
Prerequisites
This chapter assumes you already know:
- Basic TypeScript syntax: type aliases, interfaces, functions, and simple generics.
- Union and intersection types (
A | B,A & B). - The difference between compile-time types and runtime values. Types exist only while the compiler runs, and the emitted JavaScript contains none of them.
You do not need any prior knowledge of branded types.
Two ways to compare types
A type system needs a rule for answering one question: "Can a value of type S be used where type T is expected?" Languages answer it in one of two ways.
- Nominal typing compares names. Two types are compatible only if they are declared as related, for example through inheritance. Java and C# work this way for classes.
- Structural typing compares shapes. Two types are compatible if S has at least the members that T requires, with compatible types. The names and declaration sites do not matter.
TypeScript is structural. The design suits JavaScript, where code is written around objects that happen to have the right properties, often called duck typing. TypeScript's type system was built to describe that existing code instead of forcing it into class hierarchies.
| Question | Nominal typing | Structural typing (TypeScript) |
|---|---|---|
| What is compared? | The declared name or declaration | The members and their types |
| Is `type A = string` the same as `type B = string`? | Usually no, if they are declared as distinct | Yes, they are both `string` |
| Must a type declare that it implements an interface? | Yes | No, matching members are enough |
| Accidental compatibility | Rare | Possible |
Structural typing in practice
Here are two interfaces that never mention each other:
interface Point {
x: number;
y: number;
}
interface Vector {
x: number;
y: number;
}
function length(p: Point): number {
return Math.hypot(p.x, p.y);
}
const v: Vector = { x: 3, y: 4 };
console.log(length(v)); // 5length asks for a Point. A Vector has the same members, so it is accepted. No implements clause or conversion is needed. In many programs this is what you want, because a function that only reads x and y should not care what the caller named its type.
Compatibility is also directional. The source may have more members than the target needs:
interface Named {
name: string;
}
function greet(n: Named): void {
console.log(`Hello, ${n.name}`);
}
const user = { name: "Ada", id: 1 };
greet(user); // OK: user has everything Named requires, plus an extra idA type with more members is a subtype of one with fewer, and you can pass it where the smaller type is expected. This is why a wide object can flow into a narrow function parameter without a cast.
The excess property check
You may have seen an error when passing an object literal with extra properties:
interface Named {
name: string;
}
function greet(n: Named): void {
console.log(`Hello, ${n.name}`);
}
greet({ name: "Ada", id: 1 });
// Error: Object literal may only specify known properties, and 'id' does not exist in type 'Named'.This looks nominal, but it is a separate, narrow check. It applies only to fresh object literals written directly at the point of assignment, where an extra property is more likely a typo than intent. Once the object is stored in a variable (as user was above), the check no longer applies and ordinary structural compatibility takes over. Do not read the excess property check as evidence that TypeScript compares names.
Where TypeScript is nominal-like
Classes with private or protected members are an exception. Such a member has a declaration site, so two classes cannot share it by coincidence:
class Meters {
private value = 0;
}
class Seconds {
private value = 0;
}
const m: Meters = new Seconds();
// Error: Types have separate declarations of a private property 'value'.Classes with only public members stay fully structural. This behavior matters later, because it is one reason class-based wrappers can make types distinct, at a cost we cover in a later chapter.
What the compiler does with your aliases
A type alias gives an existing type a second name. It does not create a new type. Consider a program that handles users and orders:
type UserId = string;
type OrderId = string;
function loadOrder(id: OrderId): void {
console.log("loading", id);
}
const userId: UserId = "u_123";
loadOrder(userId); // compiles: both aliases are just stringWhen the compiler resolves UserId and OrderId, both become string. The question "is UserId assignable to OrderId?" is therefore "is string assignable to string?", and the answer is yes. The aliases document your intent for human readers, but the type checker never sees that intent.
The same happens with numbers:
type Celsius = number;
type Fahrenheit = number;
function boil(temp: Celsius): boolean {
return temp >= 100;
}
const oven: Fahrenheit = 212;
console.log(boil(oven)); // false, although 212 degrees Fahrenheit is exactly boilingThis compiles and runs. It also returns the wrong answer, because a Fahrenheit value was read as Celsius. Nothing in the type system flagged the mix-up.
The flow of the check looks like this:
The alias names disappear at the resolve step, before any comparison happens. Everything after that works on string.
Why this design is reasonable
It is tempting to call structural typing a flaw, but it has real benefits:
- It fits existing JavaScript. Libraries rarely declare which interfaces their objects implement. Structural typing lets you describe them after the fact.
- It makes testing and mocking easy. A test double only needs the members the code under test uses.
- It decouples modules. A consumer can define the small interface it needs, and any matching producer works without importing the producer's types.
The cost appears when two types share a shape but not a meaning. Identifiers, units, validated versus unvalidated text, and sanitized versus raw HTML all have the same shape (string or number) and different rules. The compiler compares only shapes, so it cannot tell them apart.
Common errors and misconceptions
- "My alias protects me." An alias is a label. If two aliases point at the same underlying type, they are one type.
- "An interface with a different name is a different type." Two interfaces with the same members are interchangeable. Using different names has no effect on compatibility.
- "The excess property error proves nominal typing." It is a check on fresh object literals only. Pass the same object through a variable and it disappears.
- "A function parameter named
userIdis checked by its name." Parameter and variable names are never part of type compatibility. Only the types count. - "Adding a comment or a doc tag will make the compiler complain." Comments are not types. Tools like linters can enforce conventions, but the compiler does not read them.
You may be tempted to give each ID type its own interface with a different property name, such as { userId: string } and { orderId: string }. That does make them incompatible, but it changes the runtime shape of your data and forces wrapping everywhere. The next chapters show a way to get distinct types without changing the runtime value at all.
Where this leads
You now have the rule behind the problem: TypeScript compares shapes, an alias adds no shape, and so two aliases of string are one type. The next chapter looks at this pattern, often called primitive obsession, in more detail and shows how it spreads through a codebase. After that, the chapter on intersection brands shows how to add a fake but checkable property to a primitive type, so that a UserId and an OrderId stop being compatible.
Exercise
Given type Meters = number; and type Seconds = number;, does the call move(time) compile in the code below? Explain why, and say which part of TypeScript's rules decides the result.
function move(distance: Meters): void {}
const time: Seconds = 9;
move(time);
Show answer
Yes, it compiles. Each alias resolves to number, so the compiler checks whether number is assignable to number, which it is. TypeScript uses structural typing, which compares shapes instead of names, and an alias adds no new shape. The alias names are never part of the comparison, so the mix-up of seconds for meters is not reported.
Exercise
Two interfaces, interface A { id: string } and interface B { id: string }, are declared in different files with no relationship between them. Can a value of type A be passed to a function that takes B? Then say what changes if B is instead { id: string; label: string }.
Show answer
Yes, the first case compiles, because A has every member B requires, so the two are structurally identical. In the second case it fails, because A lacks label, so A is not assignable to the larger B. Compatibility only requires that the source has at least the members the target needs, so the reverse direction (passing a B where an A is expected) would compile.