TypeScript Template Literal Types
A template literal type builds string types from unions placed inside placeholders. Each union member produces one finished literal string in the result.
Handler names from an event union
The placeholder holds the event union. Prefixing each member with on builds the handler name type.
type EventName = 'click' | 'hover' | 'focus';
type HandlerName = `on${EventName}`;
const first: HandlerName = 'onclick';
const second: HandlerName = 'onhover';
console.log(first);
console.log(second);Two unions multiply
One template can hold two placeholders. Every size pairs with every element, so two unions of two members build four strings.
type SizeName = 'small' | 'large';
type ElementName = 'button' | 'card';
type ClassName = `${SizeName}-${ElementName}`;
const first: ClassName = 'small-button';
const second: ClassName = 'large-card';
console.log(first);
console.log(second);A string outside the set is refused
The built type contains only the expanded strings. A handler name built from an event outside the union fails to compile.
type EventName = 'click' | 'hover';
type HandlerName = `on${EventName}`;
const handler: HandlerName = 'onpress';
console.log(handler);Example
type ColorName = 'red' | 'blue';
type ShadeName = 'light' | 'dark';
type TokenName = `${ShadeName}${ColorName}`;
function pick(token: TokenName): string {
return 'picked ' + token;
}
console.log(pick('lightred'));
console.log(pick('darkblue'));Key points
- A template literal type writes a string pattern with a union inside a placeholder.
- The checker expands the placeholder into one literal type per union member.
- Two placeholders in one template multiply the members of both unions.
- The result is a closed set of strings that behaves like any other literal union.
- A string outside the built set is refused with a normal assignment error.
In this example, the two unions multiply into four token names, and the pick function accepts only those four strings.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
How many members does a template type built from a union of 2 and a union of 3 produce?