0
0
Typescriptprogramming~5 mins

How structural typing differs from nominal typing in Typescript - Performance & Efficiency

Choose your learning style9 modes available
Time Complexity: How structural typing differs from nominal typing
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of properties in the types grows, the work to check compatibility grows too.

Input Size (n properties)Approx. Operations
1010 property comparisons
100100 property comparisons
10001000 property comparisons

Pattern observation: The checking work grows directly with the number of properties.

Final Time Complexity

Time Complexity: O(n)

This means the time to check types grows in a straight line with the number of properties.

Common Mistake

[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.

Interview Connect

Understanding how TypeScript checks types helps you explain how your code scales and why some checks take longer with bigger types.

Self-Check

What if TypeScript used nominal typing instead of structural typing? How would the time complexity of type checks change?