How assignment compatibility is checked in Typescript - Performance & Efficiency
We want to understand how TypeScript checks if one value can be assigned to another.
How much work does TypeScript do as types get bigger or more complex?
Analyze the time complexity of the following code snippet.
interface Point {
x: number;
y: number;
}
const p1: Point = { x: 1, y: 2 };
const p2 = { x: 3, y: 4, z: 5 };
const p3: Point = p2; // assignment compatibility check
This code checks if the object p2 can be assigned to the type Point.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each property in the target type against the source type.
- How many times: Once for each property in the target type (here, 2 properties: x and y).
As the number of properties in the target type grows, TypeScript checks each one.
| Input Size (n properties) | Approx. Operations |
|---|---|
| 10 | About 10 property checks |
| 100 | About 100 property checks |
| 1000 | About 1000 property checks |
Pattern observation: The work grows directly with the number of properties to check.
Time Complexity: O(n)
This means the checking time grows in a straight line as the number of properties increases.
[X] Wrong: "Assignment compatibility is instant no matter how big the types are."
[OK] Correct: TypeScript must check each property to be sure, so bigger types take more time.
Understanding how TypeScript checks assignment helps you reason about type safety and performance in real projects.
"What if the source type has nested objects? How would that affect the time complexity?"