Removing modifiers with minus in Typescript - Time & Space Complexity
We want to understand how fast the program runs when we remove modifiers using the minus sign in TypeScript.
How does the time to remove modifiers change as the input grows?
Analyze the time complexity of the following code snippet.
type RemoveReadonly<T> = {
-readonly [P in keyof T]: T[P]
}
const example: RemoveReadonly<{ readonly a: number; readonly b: string }> = {
a: 5,
b: 'hello'
}
This code removes the readonly modifier from all properties of a type.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Iterating over each property key in the type
T. - How many times: Once for each property in the input type.
As the number of properties increases, the time to remove modifiers grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 property removals |
| 100 | 100 property removals |
| 1000 | 1000 property removals |
Pattern observation: Doubling the number of properties roughly doubles the work done.
Time Complexity: O(n)
This means the time to remove modifiers grows directly with the number of properties.
[X] Wrong: "Removing modifiers happens instantly no matter how many properties there are."
[OK] Correct: Each property must be processed, so more properties mean more work.
Understanding how type transformations scale helps you write efficient and clear TypeScript code, a skill valued in many coding tasks.
"What if we removed multiple modifiers at once? How would the time complexity change?"