TypeScript theorytheory 0/50 · 0%
Types · hard

40. Template literal types

Building string types out of unions, like a compile-time string template.

Template literal types combine literal strings with unions to generate a set of possible string types, similar to JS template literals but evaluated by the compiler.

ts
type Chain = "eth" | "polygon" | "arb";
type Env = "main" | "test";

type Endpoint = `${Chain}-${Env}.rpc.example.com`;
// "eth-main.rpc.example.com" | "eth-test.rpc.example.com" | "polygon-main.rpc.example.com" | ... (6 combinations)

type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<"click">; // "onClick"

Combining a literal union with a template produces the cross-product of all combinations — here 3 chains × 2 environments = 6 possible endpoint strings, each individually valid at the type level. Intrinsic string manipulation types (`Uppercase`, `Lowercase`, `Capitalize`, `Uncapitalize`) are often used alongside template literals to transform casing.

Check your understanding

  1. 1. What does `` `${Chain}-${Env}.rpc.example.com` `` produce when Chain and Env are unions?

  2. 2. What does `Capitalize<T>` do?

  3. 3. How many string literal types does `` `${Chain}-${Env}...` `` produce if Chain has 3 members and Env has 2?