0
0
Typescriptprogramming~5 mins

Required type in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Required type
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

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 objects10 x 3 = 30 property accesses
100 objects100 x 3 = 300 property accesses
1000 objects1000 x 3 = 3000 property accesses

Pattern observation: The work grows linearly with the number of objects processed.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete grows directly in proportion to how many objects we convert.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if the object had 100 properties instead of 3? How would the time complexity change?"