TypeScript 7 reference · Type Operators and Keywords
TypeScript template literal types Operator
Build string literal types with template syntax: `on${string}` or combinations of unions like `${Size}-${Color}`.
TypeScript 7 Since 4.1
Syntax
`prefix${Type}suffix`
Examples
type Size = "S" | "M";
type Color = "red" | "blue";
type Sku = `${Size}-${Color}`; // 4 combinations
const all: Sku[] = ["S-red", "S-blue", "M-red", "M-blue"];
console.log(all.length);
Output
4
type CssLength = `${number}px` | `${number}rem`;
const a: CssLength = "16px";
// @ts-expect-error: must end in px or rem
const b: CssLength = "16pt";
console.log(a);
Output
16px
Version history
| Version | Change |
|---|---|
| TypeScript 4.1 | Added |
Related
Uppercase<StringType>· Turn a string literal type into upper case at the type level: Uppercase<'get'> is 'GET'.Capitalize<StringType>· Upper-case the first character of a string literal type: Capitalize<'click'> is 'Click'. Used to build names like onClick.mapped types ({ [K in Keys]: … })· Create a new object type by transforming every property of another, the way Partial and Readonly are built.- TypeScript keyof, typeof and Indexed Access · tutorial