How structural typing differs from nominal typing in Typescript - Performance & Efficiency
We want to understand how checking if two types match grows in cost as types get bigger or more complex.
How does the way TypeScript compares types affect the work it does?
Analyze the time complexity of type compatibility checks in TypeScript's structural typing.
interface Point {
x: number;
y: number;
}
interface NamedPoint {
x: number;
y: number;
name: string;
}
let p: Point = { x: 1, y: 2 };
const np: NamedPoint = { x: 1, y: 2, name: "A" };
// Structural typing allows this:
p = np;
This code shows TypeScript allowing assignment based on matching properties, not explicit names.
When TypeScript checks if one type fits another, it compares each property.
- Primary operation: Comparing each property in the source and target types.
- How many times: Once for each property in the target type.
As the number of properties in the types grows, the work to check compatibility grows too.
| Input Size (n properties) | Approx. Operations |
|---|---|
| 10 | 10 property comparisons |
| 100 | 100 property comparisons |
| 1000 | 1000 property comparisons |
Pattern observation: The checking work grows directly with the number of properties.
Time Complexity: O(n)
This means the time to check types grows in a straight line with the number of properties.
[X] Wrong: "TypeScript compares types by their names, so checking is instant."
[OK] Correct: TypeScript compares the shape (properties) of types, so it must check each property, which takes time.
Understanding how TypeScript checks types helps you explain how your code scales and why some checks take longer with bigger types.
What if TypeScript used nominal typing instead of structural typing? How would the time complexity of type checks change?