Readonly utility type in Typescript - Time & Space Complexity
We want to understand how the time it takes to use the Readonly utility type changes as the size of the object grows.
Specifically, how does making an object readonly affect the number of operations when the object has many properties?
Analyze the time complexity of the following code snippet.
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
interface User {
name: string;
age: number;
email: string;
}
const user: Readonly<User> = {
name: "Alice",
age: 30,
email: "alice@example.com"
};
This code creates a readonly version of a User object by applying the Readonly utility type to all its properties.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The mapped type loops over each property key in the object type.
- How many times: Once for each property in the object (for example, 3 times for User).
As the number of properties in the object grows, the number of operations grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 (one per property) |
| 10 | 10 |
| 100 | 100 |
Pattern observation: The operations increase directly with the number of properties, growing in a straight line.
Time Complexity: O(n)
This means the time to create a readonly type grows linearly with the number of properties in the object.
[X] Wrong: "Making an object readonly happens instantly no matter how big it is."
[OK] Correct: The type system processes each property one by one, so more properties mean more work.
Understanding how utility types like Readonly work helps you reason about type transformations and their costs, a useful skill in real projects and interviews.
"What if we changed Readonly to make only some properties readonly? How would the time complexity change?"