0
0
Typescriptprogramming~5 mins

Type alias for unions in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Type alias for unions
O(1)
Understanding Time Complexity

Let's see how the time it takes to run code changes when we use type aliases for unions in TypeScript.

We want to know how the program's work grows as the input size changes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


    type Status = "success" | "error" | "loading";

    function handleStatus(status: Status) {
      switch (status) {
        case "success":
          return "Operation succeeded";
        case "error":
          return "Operation failed";
        case "loading":
          return "Loading...";
      }
    }
    

This code defines a type alias for a union of string literals and uses it in a function with a switch-case to handle each case.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The switch statement checks the input once per function call.
  • How many times: Exactly one time per call; no loops or recursion.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The switch performs a constant number of operations regardless of input size.

Final Time Complexity

Time Complexity: O(1)

This means the time to run remains constant regardless of the input size.

Common Mistake

[X] Wrong: "Using a union type alias makes the function run faster because it limits options."

[OK] Correct: The type alias helps with code clarity and safety but does not change how many checks the function does at runtime.

Interview Connect

Understanding how type aliases affect runtime helps you explain code clarity versus performance, a useful skill in real projects and interviews.

Self-Check

What if we added more cases to the union type? How would the time complexity change?