A template literal type is the backtick syntax used in a type: `${A}-${B}`. It does three jobs.
- Build string unions. Placeholders that are literal types are concatenated. Union placeholders are cross-multiplied, so
`${"en" | "ja"}_${"title" | "body"}`is four literals. This is how you derive event names (`${K}Changed`) or CSS-like tokens from existing unions. - Describe a string pattern. A placeholder of
string,numberorbigintmakes a non-literal pattern (booleanjust expands to"true" | "false", checked):`${number}px`accepts"12px"and rejects"12em";`--${string}`accepts any string with that prefix. Patterns also work as mapped-type key sources, e.g.`data-${string}`. - Parse strings with
infer. In a conditional type,S extends `${infer A}-${infer B}`splits the string.Atakes the shortest match up to the first delimiter and the last placeholder takes the rest. With adjacent placeholders each non-finalinfercaptures a single character. Addinfer N extends number(TS 4.8) to turn"42"into the literal42.
Intrinsic string types. Uppercase, Lowercase, Capitalize, Uncapitalize are implemented inside the compiler (intrinsic in lib.es5.d.ts; PR 40580), not in TypeScript. They distribute over unions and are the usual way to turn name into getName.
Constraints. Placeholders must be string | number | bigint | boolean | null | undefined; use string & K for a key type that may include symbols. A union in each position multiplies, and the compiler errors (TS2590) when the result becomes too large, so generate big sets ahead of time instead.
Typical uses: typed event or route names, parsing route params (/users/:id), typed on("xChanged") APIs, CSS unit strings, and key renaming in mapped types.