Structural vs Nominal Typing
What you'll learn: You'll understand why TypeScript considers two types with identical properties to be the same type, even when they have different names.
The Core Concept
TypeScript uses structural typing (also called "duck typing"). This means the type checker only cares about the shape of an object—what properties it has and their types—not what the type is named.
In contrast, nominal typing (used in languages like Java or C#) considers types different if they have different names, even if their structure is identical.
How Structural Typing Works
In TypeScript, if two types have the exact same structure, they're interchangeable:
interface Cat {
name: string;
meow(): void;
}
interface Dog {
name: string;
meow(): void;
}
const cat: Cat = { name: "Whiskers", meow: () => console.log("meow") };
const dog: Dog = cat; // ✅ No error! They have the same shape.
Even though Cat and Dog are different names, TypeScript sees them as compatible because they have identical properties.
Why This Matters
This can be surprising when you want types to be distinct for business logic reasons:
interface UserId {
value: string;
}
interface OrderId {
value: string;
}
function processOrder(orderId: OrderId) {
// ...
}
const userId: UserId = { value: "user-123" };
processOrder(userId); // ✅ TypeScript allows this!
TypeScript doesn't stop you from passing a UserId where an OrderId is expected because structurally, they're identical—both just wrap a string in a value property.
The JavaScript Philosophy
This design reflects JavaScript's dynamic nature. In JavaScript, you never check "is this a Cat object?" but rather "does this object have the properties I need?" TypeScript extends this philosophy to its type system.
Key Takeaway: TypeScript's structural type system treats types as compatible when their shapes match, regardless of their names—this enables flexibility but can surprise developers expecting nominal type checking.