Template literals with unions let you create flexible string types by combining fixed parts with a set of options. This helps catch mistakes and makes your code clearer.
0
0
Template literal with unions in Typescript
Introduction
When you want to allow only specific string patterns made from fixed words and choices.
When you want to build URLs or commands that follow certain formats.
When you want to restrict input to a few allowed string combinations.
When you want to improve code readability by naming common string patterns.
When you want TypeScript to check your strings for correctness automatically.
Syntax
Typescript
type Greeting = `Hello, ${'Alice' | 'Bob' | 'Eve'}`;The backticks `` create a template literal type.
The ${} part lets you insert a union of string options.
Examples
This creates strings like 'Size is small', 'Size is medium', or 'Size is large'.
Typescript
type Size = 'small' | 'medium' | 'large'; type Message = `Size is ${Size}`;
This creates strings like 'red-on', 'green-off', etc.
Typescript
type Color = 'red' | 'green'; type Status = 'on' | 'off'; type Light = `${Color}-${Status}`;
This creates strings like 'move-up' or 'move-down'.
Typescript
type Direction = 'up' | 'down'; type Command = `move-${Direction}`;
Sample Program
This program defines an order type combining quantity and fruit. It prints the order if it matches allowed patterns. Trying to use a wrong quantity causes an error.
Typescript
type Fruit = 'apple' | 'banana' | 'cherry'; type Quantity = 'one' | 'two' | 'three'; type Order = `${Quantity} ${Fruit}`; function printOrder(order: Order) { console.log(`You ordered: ${order}`); } printOrder('two banana'); // printOrder('four apple'); // Error: 'four' not allowed
OutputSuccess
Important Notes
Template literal types only work with string unions inside ${}.
TypeScript checks these types at compile time, not at runtime.
You can combine multiple unions to create many string options easily.
Summary
Template literal with unions helps create specific string patterns.
It improves code safety by limiting allowed string values.
Use it to combine fixed text with choices for clear, checked strings.