Template literal types
type EventName<T extends string> = `${T}Changed`;
type Handler<T extends string> = `on${Capitalize<T>}`;Build new string literal types from existing ones. Unions in interpolations expand to every combination.
| Type parameter | Description |
|---|---|
T | Usually a string literal or a union of literals. A constraint such as extends string keeps the template from accepting unrelated types. |
Produces: A string literal type, or a union of them when the input interpolations are unions.
Type errors
type error— A string that does not match the resulting literal union is not assignable, such as "onclick" where the type requires "onClick".
- Template literal types were added in TypeScript 4.1. They exist only at compile time.
type EventName<T extends string> = `${T}Changed`;
type Handler<T extends string> = `on${Capitalize<T>}`;
const ev: EventName<"foo"> = "fooChanged";
const click: Handler<"click" | "focus"> = "onClick";
const focusEvent: Handler<"click" | "focus"> = "onFocus";
// @ts-expect-error "onclick" is not Capitalize<"click">
const bad: Handler<"click"> = "onclick";
// @ts-expect-error the union does not include "change"
const missing: EventName<"foo" | "bar"> = "changeChanged";
type Cross = `${"a" | "b"}-${"1" | "2"}`;
const c: Cross = "a-1";
console.log(ev, click, c);Expected output
fooChanged onClick a-1Related: Capitalize, Mapped key remapping