0
0
Typescriptprogramming~5 mins

Phantom types in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Phantom types
O(1)
Understanding Time Complexity

We want to see how using phantom types affects the speed of our TypeScript code.

Specifically, does adding phantom types change how long the program takes as input grows?

Scenario Under Consideration

Analyze the time complexity of the following TypeScript code using phantom types.


    type Phantom<T> = { _phantom?: T };

    function addLengths<T>(a: string & Phantom<T>, b: string & Phantom<T>): number {
      return a.length + b.length;
    }

    const s1 = "hello" as string & Phantom<'A'>;
    const s2 = "world" as string & Phantom<'A'>;
    console.log(addLengths(s1, s2));
    

This code uses phantom types to tag strings without changing runtime behavior.

Identify Repeating Operations

Look for loops or repeated steps that affect speed.

  • Primary operation: Calculating string lengths with a.length and b.length.
  • How many times: Each length is accessed once per function call.
How Execution Grows With Input

As input strings get longer, the time to get their length grows very little because length is a stored property.

Input Size (n)Approx. Operations
102 length checks
1002 length checks
10002 length checks

Pattern observation: The number of operations stays the same no matter how long the strings are.

Final Time Complexity

Time Complexity: O(1)

This means the function runs in constant time regardless of input size.

Common Mistake

[X] Wrong: "Phantom types add extra work at runtime and slow down the program."

[OK] Correct: Phantom types exist only at compile time and do not affect runtime speed or operations.

Interview Connect

Understanding phantom types helps you write safer code without slowing it down, a skill valued in real projects.

Self-Check

What if the function processed each character of the strings instead of just their lengths? How would the time complexity change?