typestar

Template literal types in TypeScript

String types built from other string types, at compile time.

type Lang = "go" | "ts";
type Tour = "basics" | "async";

type Route = `/${Lang}/${Tour}`;
type EventName = `on${Capitalize<Tour>}`;
type CssVar = `--${string}`;

type ParseRoute<T extends string> =
  T extends `/${infer L}/${infer S}` ? { lang: L; tour: S } : never;

type Parsed = ParseRoute<"/go/basics">;

const route: Route = "/ts/async";
const handler: EventName = "onBasics";
const variable: CssVar = "--accent";
const parsed: Parsed = { lang: "go", tour: "basics" };
console.log(route, handler, variable, parsed.lang);

How it works

  1. Interpolating a union produces every combination.
  2. Uppercase, Capitalize and friends transform them.
  3. infer inside a pattern parses a string type apart.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
524
Tokens
145
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 79 seconds.

Type this snippet

Step 1 of 2 in Strings & recursion, step 7 of 12 in Type-level programming.

← Previous Next →