0
0
Typescriptprogramming~5 mins

Literal types and value narrowing in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Literal types and value narrowing
O(1)
Understanding Time Complexity

Let's explore how the time it takes to run code changes when we use literal types and value narrowing in TypeScript.

We want to see how the program's steps grow as input changes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function checkStatus(status: "success" | "error" | "loading") {
  if (status === "success") {
    return "Operation succeeded";
  } else if (status === "error") {
    return "Operation failed";
  } else {
    return "Loading...";
  }
}
    

This code checks a status value narrowed to specific words and returns a message accordingly.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Simple conditional checks comparing the input value.
  • How many times: Each check happens once per function call.
How Execution Grows With Input

Since the function only checks fixed possible values, the steps do not increase with input size.

Input Size (n)Approx. Operations
1Up to 3 checks
10Up to 3 checks per call, total up to 30 if called 10 times
1000Up to 3 checks per call, total up to 3000 if called 1000 times

Pattern observation: Each call does a fixed small number of steps, so complexity stays the same per call.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the function does not grow with input size; it stays constant.

Common Mistake

[X] Wrong: "Since there are multiple checks, the time grows with the number of possible values."

[OK] Correct: The checks are fixed and do not depend on input size; they always run the same small number of times.

Interview Connect

Understanding how narrowing values affects performance helps you write clear and efficient code, a skill valued in real projects and interviews.

Self-Check

What if we added more possible literal values to the status type? How would the time complexity change?