Type alias for unions in Typescript - Time & Space 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.
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 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.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The switch performs a constant number of operations regardless of input size.
Time Complexity: O(1)
This means the time to run remains constant regardless of the input size.
[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.
Understanding how type aliases affect runtime helps you explain code clarity versus performance, a useful skill in real projects and interviews.
What if we added more cases to the union type? How would the time complexity change?