Template literal types in Typescript - Time & Space Complexity
We want to understand how the time it takes to work with template literal types changes as the input grows.
Specifically, how does the process of creating or checking these types scale with input size?
Analyze the time complexity of the following code snippet.
type EventName = `${T}Changed`;
type UserEvent = EventName<'name' | 'age' | 'email'>;
This code creates new string types by adding "Changed" to each string in a union.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Applying the template literal to each string in the union.
- How many times: Once for each string in the union type.
As the number of strings in the union grows, the number of new types created grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 | 3 (one for each string) |
| 10 | 10 |
| 100 | 100 |
Pattern observation: The work grows directly with the number of strings in the union.
Time Complexity: O(n)
This means the time to process grows in a straight line with the number of strings.
[X] Wrong: "Template literal types combine all strings instantly without extra work for each."
[OK] Correct: Each string in the union must be processed separately, so the work adds up with more strings.
Understanding how template literal types scale helps you reason about type operations in TypeScript, a useful skill for writing clear and efficient code.
"What if we nested template literal types inside each other? How would the time complexity change?"