QA Interview Hub · Knowledge base · Quizzes · Українська

TypeScript › Advanced types: keyof, typeof, mapped, conditional, template literal

Template literal types

Template literal types describe a string pattern at the type level, like a template string in code, so the compiler checks a key format before running. Given a union they produce every combination, and infer can extract parts of the string, such as path parameters. Only literals known at compile time are checked: external data has type string and is validated at runtime.

TypeScript · Advanced types

A mock helper accepts the string "POST /transfers" while the real route is /api/v1/transfers. How do we teach the type to tell them apart?

A helper registers a mock for a request: mock('POST /api/v1/transfers', handler). The key is a string, and a typo in it breaks nothing visibly: the handler quietly never fires while the test waits for a response. The type string does not know what is allowed here. This lesson covers template literal types: string types built from a template that check the format before the code runs.

How it works and why. A template literal type is written like a template string, only at the type level: `/api/${Version}/${string}`. The substitution can hold literal types, unions, string, number or bigint. When a union is substituted, you get every combination (a Cartesian product): two methods times two versions make four string types. ${string} means "any string in this position", ${number} any string that parses as a number. The built-in utilities Uppercase, Lowercase, Capitalize, Uncapitalize change the case of a literal.

A template and its combinations

Method = 'GET' | 'POST'2 variantsVersion = 'v1' | 'v2'2 variants`${Method} /api/${Version}/…`2 × 2 = 4 string types
Figure 1. A template over a union does not write every variant by hand: the compiler builds them.

A separate feature: infer inside a template extracts parts of a string, like a regular expression but at the type level. More on that below.

Example: a key that accepts anything. A helper with a string key:

const handlers: Record<string, Handler> = {};

function mock(key: string, handler: Handler) {
  handlers[key] = handler;
}

mock('POST /api/v1/transfer', createTransfer);
mock('POST /transfers', createTransfer);

Both calls compile. In the first there is a typo, transfer instead of transfers, and in the second the /api/v1 prefix is missing. Keys that no request matches got into the registry, so the handlers never run, and the test waits for a response that does not come.

The fix: describe the allowed key format with a type.

type Method = 'GET' | 'POST' | 'PUT' | 'DELETE';
type Version = 'v1' | 'v2';
type ApiPath = `/api/${Version}/${string}`;
type RouteKey = `${Method} ${ApiPath}`;

const ok: RouteKey = 'POST /api/v1/transfers';
const bad: RouteKey = 'POST /transfers'; // compile error
const handlers: Partial<Record<RouteKey, Handler>> = {
  'GET /api/v1/accounts': listAccounts,
  'POST /api/v1/transfers': createTransfer,
};

function mock(key: RouteKey, handler: Handler) {
  handlers[key] = handler;
}

Now the key 'POST /transfers' does not compile, and the editor suggests the method and the prefix. The convention is written once in a type and works in every call.

A route key

Wrong

key: string

Any string passes. A typo becomes a dead handler and a test that waits for nothing.

Right

key: RouteKey

The compiler checks the format: the method and the /api/v1 prefix.

Figure 2. A template type moves the convention from a comment into compilation.

Extracting parts of a string. Sometimes a format is worth not only checking but parsing. The path parameters can be extracted straight from the route string:

type Params<P extends string> =
  P extends `${string}:${infer Name}/${infer Rest}`
    ? Name | Params<`/${Rest}`>
    : P extends `${string}:${infer Name}`
      ? Name
      : never;

function route<P extends string>(
  path: P,
  handler: (params: Record<Params<P>, string>) => void,
) {}

route('/accounts/:id/transfers/:tid', (p) => {
  console.log(p.id, p.tid);
});

The type Params looks in the template for a :Name section up to the next / and processes the rest recursively. For '/accounts/:id/transfers/:tid' the result is 'id' | 'tid', so handler receives an object with the keys id and tid, and access to a nonexistent parameter does not compile. For a path without parameters the result is never, that is an empty object.

Other useful applications. Conventions checked by the compiler:

type TestId = `${'btn' | 'input' | 'row'}-${string}`;
type TransferEvent = `transfer.${'created' | 'completed' | 'failed'}`;
type IsoDate = `${number}-${number}-${number}`;
type Env = 'dev' | 'stage';
type BaseUrl = `https://${Env}.bank.example`;

TestId enforces prefixes in a helper over getByTestId. TransferEvent describes event or metric keys. IsoDate gives a rough restriction that catches obvious mistakes but does not validate a date: the string '1-2-3' passes too.

Limits and alternatives.

  • Template types work only with literals known at compile time. A string from process.env or from an API response has type string and still has to be checked at runtime (a type guard, a schema, a regular expression).
  • Combinations multiply: three unions of ten members each make a thousand string types. The compiler has a limit on union size and complains when it is exceeded, and large unions slow the build.
  • Types do not validate values: ${number} accepts '1e3' and '-0'. For strict validation (a date, an email, an IBAN) a function is needed, and the type only helps.
  • Recursive templates are hard to read, so they are confined to the library layer and documented with a usage example.

Common mistakes.

  • Thinking IsoDate validates a date: it checks only the shape "number-number-number".
  • Expecting an error on a value from process.env: it has type string, not a literal.
  • Generating huge unions with a template: the build slows down and the compiler may refuse.
  • Forgetting as const for a variable later passed to a function with a template type: const key = 'GET /api/v1/x' keeps the literal, while let key = … widens to string.

Check yourself

The string const url = process.env.API_URL is passed to a function that accepts `https://${Env}.bank.example`. Why does the compiler reject it, and what should be done?

Answer

A value from process.env has type string | undefined, while a template type accepts only literals of a known shape. Data from outside is checked at runtime (a type guard or a schema), and only then is the type narrowed.

How many string types does `${'GET' | 'POST'} /v${1 | 2 | 3}` give, and why does it matter?

Answer

Six: 2 × 3. A template over unions gives every combination, so the result size multiplies, and with large unions the compiler slows down or reports a type that is too complex.

In an interview. Junior: Template literal types set a string template at the type level, for example a method plus a path that starts with /api/. For unions they give all combinations. Middle/Senior: I use them for conventions (route keys, test ids, environment URLs), and with infer I extract, for example, path parameters. But it is compile time only: data from outside has type string and is validated separately, and large combinations slow the build.

More articles in this chapter