Template Literal Type Basics

Strings Built From Types

Template literal types use the same backtick syntax as JavaScript template strings, but with types inside ${...}. With unions, every combination is generated.

Example

The error lists all generated combinations of size and colour.

type Size = "S" | "M" | "L";
type Color = "black" | "white";
type Sku = `TSHIRT-${Size}-${Color}`;

const ok: Sku = "TSHIRT-M-black";
const bad: Sku = "TSHIRT-XL-red";

Compiler output (tsc)

Line 6: error TS2322: Type '"TSHIRT-XL-red"' is not assignable to type '"TSHIRT-S-black" | "TSHIRT-S-white" | "TSHIRT-M-black" | "TSHIRT-M-white" | "TSHIRT-L-black" | "TSHIRT-L-white"'.

Intrinsic String Types

Example

Uppercase, Lowercase, Capitalize and Uncapitalize transform string literal types. `${number}px` accepts any number followed by px.

type Method = "get" | "post";
type UpperMethod = Uppercase<Method>;          // "GET" | "POST"
type Handler = `on${Capitalize<"click" | "submit">}`; // "onClick" | "onSubmit"
type Px = `${number}px`;
type ApiVersion = `v${1 | 2}`;

const m: UpperMethod = "POST";
const h: Handler = "onSubmit";
const width: Px = "240px";
const version: ApiVersion = "v2";

function css(prop: string, value: Px): string { return `${prop}: ${value};`; }
console.log(m, h, version, css("width", width));

Output

POST onSubmit v2 width: 240px;