Pick type in Typescript - Time & Space Complexity
Let's see how the time it takes to create a new type using Pick changes as the number of keys grows.
We want to know how the work grows when we pick more properties from a type.
Analyze the time complexity of this TypeScript type operation.
type Original = {
a: string;
b: number;
c: boolean;
d: Date;
e: string[];
};
type Picked = Pick;
This code creates a new type by selecting some keys from an existing type.
What happens behind the scenes when Pick runs?
- Primary operation: Iterating over the keys to select the chosen ones.
- How many times: Once for each key you pick.
As the number of keys to pick grows, the work grows too.
| Input Size (number of keys) | Approx. Operations |
|---|---|
| 3 | 3 checks |
| 10 | 10 checks |
| 100 | 100 checks |
Pattern observation: The work grows directly with the number of keys you pick.
Time Complexity: O(n)
This means the time to create the picked type grows linearly with the number of keys selected.
[X] Wrong: "Pick runs instantly no matter how many keys are selected."
[OK] Correct: Even though it's fast, Pick must check each key to include it, so more keys mean more work.
Understanding how type operations scale helps you reason about code maintainability and performance in larger projects.
What if we used a type that picks keys conditionally instead of explicitly? How would that affect time complexity?