How does embedding a union of literal types inside a template literal type produce a new union?
Short answer
When you embed a union type inside `${...}`, TypeScript computes the CROSS PRODUCT of every combination, producing a new union of every possible resulting string literal — this happens automatically, without any extra syntax needed.
Advertisement
AModel answer
When you embed a union type inside `${...}`, TypeScript computes the CROSS PRODUCT of every combination, producing a new union of every possible resulting string literal — this happens automatically, without any extra syntax needed.
type Size = 'small' | 'medium' | 'large';
type ClassName = `btn-${Size}`;
// 'btn-small' | 'btn-medium' | 'btn-large'Real-world example
Generating a precise union of valid CSS class names or Tailwind utility classes from a smaller set of literal building blocks.
Likely follow-ups
- What happens if you combine TWO different union types inside the same template literal type?
Related topics