Required type in Typescript - Time & Space Complexity
Let's see how the time it takes to run code changes when we use the Required type in TypeScript.
We want to know how the program's work grows as the input gets bigger.
Analyze the time complexity of the following code snippet.
interface Person {
name?: string;
age?: number;
city?: string;
}
function makeRequired(obj: Person): Required<Person> {
return {
name: obj.name!,
age: obj.age!,
city: obj.city!
};
}
This code takes an object with optional properties and returns a new object where all properties are required.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing each property once to assign it to the new object.
- How many times: Exactly once per property (3 properties here).
Since the number of properties is fixed, the work per object stays the same no matter how many objects we process.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 objects | 10 x 3 = 30 property accesses |
| 100 objects | 100 x 3 = 300 property accesses |
| 1000 objects | 1000 x 3 = 3000 property accesses |
Pattern observation: The work grows linearly with the number of objects processed.
Time Complexity: O(n)
This means the time to complete grows directly in proportion to how many objects we convert.
[X] Wrong: "Using Required type makes the code slower because it forces extra checks at runtime."
[OK] Correct: Required is a compile-time tool that changes types but does not add runtime loops or checks; the runtime cost depends on how many objects you process, not on the type itself.
Understanding how type utilities like Required affect your code helps you write clear and efficient programs, a skill that shows you think about both correctness and performance.
"What if the object had 100 properties instead of 3? How would the time complexity change?"