Template literal with unions in Typescript - Time & Space Complexity
We want to understand how the time it takes to create strings using template literals with unions changes as the input size grows.
Specifically, how does the number of possible string combinations affect the work done?
Analyze the time complexity of the following code snippet.
type Colors = "red" | "green" | "blue";
type Sizes = "small" | "medium" | "large";
type Shirt = `${Colors}-${Sizes}`;
function getAllShirts(): Shirt[] {
const colors: Colors[] = ["red", "green", "blue"];
const sizes: Sizes[] = ["small", "medium", "large"];
const shirts: Shirt[] = [];
for (const color of colors) {
for (const size of sizes) {
shirts.push(`${color}-${size}` as Shirt);
}
}
return shirts;
}
This code creates all possible shirt descriptions by combining colors and sizes using template literals with union types.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops over colors and sizes arrays.
- How many times: Outer loop runs once per color, inner loop runs once per size, total runs = colors x sizes.
As the number of colors and sizes grows, the total combinations grow by multiplying these counts.
| Input Size (colors x sizes) | Approx. Operations |
|---|---|
| 10 (e.g., 5 colors x 2 sizes) | 10 string creations |
| 100 (e.g., 10 colors x 10 sizes) | 100 string creations |
| 1000 (e.g., 20 colors x 50 sizes) | 1000 string creations |
Pattern observation: The work grows proportionally to the product of the input sizes.
Time Complexity: O(n * m)
This means the time grows proportionally to the number of colors times the number of sizes.
[X] Wrong: "The time grows only with the number of colors or sizes, not both."
[OK] Correct: Because the code combines every color with every size, the total work depends on both inputs multiplied together, not just one.
Understanding how nested loops multiply work helps you explain performance clearly and shows you can reason about combinations in code.
"What if we added a third union type for styles and nested another loop? How would the time complexity change?"
Practice
Which of the following best describes a template literal with unions in TypeScript?
Solution
Step 1: Understand template literals and unions
Template literals allow embedding expressions in strings. Union types restrict values to a set of options.Step 2: Combine both concepts
Template literal with unions creates strings with fixed parts and limited variable parts, improving type safety.Final Answer:
A way to create specific string patterns by combining fixed text and union types. -> Option BQuick Check:
Template literal + union = specific string patterns [OK]
- Confusing unions with simple string concatenation
- Ignoring type safety benefits
- Thinking it's only about functions
Which of the following TypeScript declarations correctly uses a template literal with unions?
type Size = "small" | "medium" | "large";
type Message = `Size is ${Size}`;Solution
Step 1: Check the union type used inside template literal
The union typeSizeis "small" | "medium" | "large" and should be used inside the template literal.Step 2: Match the template literal syntax
The correct syntax is`Size is ${Size}`to restrict the string to those sizes.Final Answer:
type Message = `Size is ${Size}`; -> Option DQuick Check:
Use union type inside template literal exactly [OK]
- Replacing union with general types like string or number
- Using incorrect syntax for template literals
- Forgetting backticks around the template
What is the type of result in the following code?
type Color = "red" | "green" | "blue";
type Alert = `Alert: ${Color}`;
const result: Alert = "Alert: green";Solution
Step 1: Understand the template literal with union
The typeAlertcreates strings by combining "Alert: " with each value inColor.Step 2: Expand the union to all possible strings
SoAlertis the union of "Alert: red", "Alert: green", and "Alert: blue".Final Answer:
"Alert: red" | "Alert: green" | "Alert: blue" -> Option AQuick Check:
Template literal expands union to all combined strings [OK]
- Assuming only one string value is allowed
- Confusing union with single string
- Using general string type instead of union
Identify the error in this TypeScript code using template literals with unions:
type Status = "success" | "error";
type Message = `Status: ${string}`;
const msg: Message = "Status: success";Solution
Step 1: Check the template literal type definition
The template literal uses${string}which allows any string, not restricted toStatus.Step 2: Identify the correct usage
It should use${Status}to restrict values to "success" or "error" only.Final Answer:
Usingstringinside template literal instead of union typeStatus. -> Option AQuick Check:
Use union type inside template literal for safety [OK]
- Using
stringinstead of union type inside template - Ignoring type safety benefits
- Confusing string literals with template literals
Given the following types, which of these assignments is valid without TypeScript errors?
type Direction = "up" | "down";
type Action = "move" | "stop";
type Command = `${Action}-${Direction}`;
const cmd1: Command = "move-up";
const cmd2: Command = "stop-left";
const cmd3: Command = "move-down";
const cmd4: Command = "jump-up";Solution
Step 1: Understand the
CommandtypeCommandis a template literal combiningActionandDirectionwith a dash, so valid strings are "move-up", "move-down", "stop-up", "stop-down".Step 2: Check each assignment
cmd1= "move-up" (valid),cmd2= "stop-left" (invalid, "left" not in Direction),cmd3= "move-down" (valid),cmd4= "jump-up" (invalid, "jump" not in Action).Final Answer:
Only cmd1 and cmd3 are valid. -> Option CQuick Check:
Match both parts to union values exactly [OK]
- Assuming any string with dash is valid
- Ignoring union type restrictions
- Confusing Action and Direction values
Ready to prove it?
Pass the test and this pattern moves unknown
