0
0
Typescriptprogramming~5 mins

Extract type in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Extract type
O(n)
Understanding Time Complexity

Let's see how the time it takes to run code using the Extract type changes as the input grows.

We want to know how the work done scales when extracting types from bigger sets.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


type Extract<T, U> = T extends U ? T : never;

// Example usage:
type Result = Extract<'a' | 'b' | 'c', 'a' | 'c'>;
// Result is 'a' | 'c'
    

This code picks types from T that are assignable to U, filtering the union types.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking each member of the union type T against U.
  • How many times: Once for each member in the union T.
How Execution Grows With Input

Each additional type in T means one more check against U.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The work grows directly with the number of types in T.

Final Time Complexity

Time Complexity: O(n)

This means the time to extract types grows linearly with the number of types in the input.

Common Mistake

[X] Wrong: "Extract type runs instantly no matter how many types are in the union."

[OK] Correct: Each type in the union must be checked, so more types mean more work.

Interview Connect

Understanding how type operations scale helps you reason about code performance and complexity in real projects.

Self-Check

"What if we changed the Extract type to check against multiple types in U? How would the time complexity change?"