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

TypeScript

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

keyof, typeof and indexed access

keyof T gives a union of a type's keys, typeof in a type position takes the type of a variable or constant, and T[K] gives a field's type by key. Together they derive a type from one source of truth: keyof typeof ROUTES gives the exact route names, so a typo becomes a compile error. It is not the runtime typeof operator, and without as const field values widen to string.

TypeScript · Advanced types

goTo(page, "acounts") compiles and the test goes to undefined. How do we make the compiler catch a typo in a route name?

A helper goTo(page, name) takes a path from a routes table. Someone wrote 'acounts', the compiler said nothing, and page.goto(undefined) failed at runtime with an unclear message. The routes table and the type of a route name live apart and drift. This lesson covers three operators that derive a type from one source of truth: keyof, typeof in a type position, and indexed access T[K].

How it works and why. keyof T gives a union of the keys of a type: for { login: …, accounts: … } it is 'login' | 'accounts'. typeof value in a type position takes the static type of a variable or constant. T[K] gives the type of a field by key (or a union of types if there are several keys). The idea is that a value already in the code becomes the single description: the type is derived, not copied. Add a route to the object and it is immediately available in types with no second edit.

From a value to a type

ROUTESa runtime value: an as const objecttypeof ROUTESthe type of that objectkeyof typeof ROUTESa union of keys: 'login' | 'accounts'(typeof ROUTES)[RouteName]a union of values: the paths
Figure 1. One as const object produces both the type of keys and the type of values.

A word about typeof. In the expression typeof x === 'string' it is a JavaScript operator that returns a string at runtime. In a type position type T = typeof x it is a TypeScript operator that takes the type of a variable and disappears after compilation. The syntax is the same, the meaning differs.

Example: a table that does not know its keys. Typical code where the table was described as Record<string, string>:

const ROUTES: Record<string, string> = {
  login: '/login',
  accounts: '/accounts',
  transfers: '/transfers/new',
};

async function goTo(page: Page, name: string) {
  await page.goto(ROUTES[name]);
}

await goTo(page, 'acounts'); // compiles, page.goto(undefined)

The type Record<string, string> says any string is a key with a string value. So ROUTES[name] has type string, although at runtime for 'acounts' it is undefined. The compiler does not know which keys really exist. The common "fix" ROUTES[name as keyof typeof ROUTES] only silences the error, it does not remove the cause.

The fix: describe the table as a constant with as const and derive the name type from it.

const ROUTES = {
  login: '/login',
  accounts: '/accounts',
  transfers: '/transfers/new',
} as const;

type RouteName = keyof typeof ROUTES;
type RoutePath = (typeof ROUTES)[RouteName];

async function goTo(page: Page, name: RouteName) {
  await page.goto(ROUTES[name]);
}

await goTo(page, 'acounts'); // compile error

as const makes values literals and readonly, so typeof ROUTES holds the exact keys and RoutePath is the union '/login' | '/accounts' | '/transfers/new'. A typo is now a compile error, and a new route is automatically available in goTo and in editor hints.

Where the name type comes from

Wrong

Record<string, string> and name: string

The compiler does not know the keys. A typo passes and the error is visible only at runtime.

Right

as const and keyof typeof

The key type is derived from the table itself. A typo does not build, a new key is added by itself.

Figure 2. One object instead of two copies: value and type do not drift.

The same trick for test data. Users, roles, currencies: one object or array, and everything else is derived:

const testUsers = {
  admin: { email: 'admin@test.io', role: 'admin' },
  operator: { email: 'op@test.io', role: 'operator' },
} as const;

type TestUserKey = keyof typeof testUsers;
type Role = (typeof testUsers)[TestUserKey]['role'];

const CURRENCIES = ['UAH', 'USD', 'EUR'] as const;
type Currency = (typeof CURRENCIES)[number];

A fixture or helper takes TestUserKey, and typos in roles disappear. For an array as const makes a tuple, and (typeof CURRENCIES)[number] gives a union of its elements. Indexed access also works with nested types: Account['owner']['address'].

Limits and alternatives.

  • keyof of a type with an index signature ({ [k: string]: number }) gives string | number, because numeric keys in JavaScript become strings. Such a type is of no use, so for a known set of keys you need an exact type.
  • Object.keys returns string[], not keyof T. This is deliberate: under structural typing an object may have extra keys. If you are sure it does not, an explicit cast is needed:
const keys = Object.keys(testUsers); // string[]

for (const key of Object.keys(testUsers) as TestUserKey[]) {
  console.log(testUsers[key].email);
}
  • satisfies serves the same goals: {…} as const satisfies Record<string, string> checks the shape of the table without losing the exact literals.
  • If the source of truth is external (OpenAPI, a GraphQL schema), key types are better generated from it, not from test code.

Common mistakes.

  • A table without as const: values widen to string, and keyof gives keys but T[K] is no longer literals.
  • Record<string, V> instead of an exact type: any key passes.
  • A cast as keyof typeof X on an arbitrary string: there is no check, only a promise to the compiler.
  • Mixing a value and a type: keyof ROUTES without typeof does not compile, because ROUTES is a value.

Check yourself

Why does keyof ROUTES not compile while keyof typeof ROUTES works?

Answer

ROUTES is a value, and keyof works with types. The typeof operator in a type position turns the value into its type, and keyof then takes the keys from it.

A table is declared as const R = { a: '/a', b: '/b' } without as const. What type does (typeof R)[keyof typeof R] give, and why is that not what goto needs?

Answer

The values are widened to string, so the result is just string. With as const it would be '/a' | '/b', and a path type would tell valid paths apart from arbitrary strings.

In an interview. Junior: keyof typeof CONFIG gives a union of the keys of a constant object, and T[K] the type of a value. I type routes, roles and test users this way so there is one object as the source of truth and no typos in strings. Middle/Senior: I remember that typeof in a type and in an expression are different operators, that Object.keys returns string[] on purpose, and that without as const values widen and type derivation loses its point.

Mapped types and conditional types

A mapped type walks over the keys of keyof T to build a new type, and a conditional type is an if at the type level. This derives one type from a model, so two descriptions cannot drift apart: Partial, Readonly, Exclude and Extract are built this way. Complex types give complex errors, so they stay in the framework layer and tests use simpler ones.

TypeScript · Advanced types

The holds field was added to Balance, and getHolds in BalanceApi was forgotten. How do we make a type follow the model?

The model Balance has three fields, and the client interface BalanceApi is written by hand with a method per field. holds was added and nobody wrote a method for it: the compiler did not notice, because the two descriptions are linked only by human attention. This lesson covers mapped types and conditional types: how to build a type from another one, what they rest on, and where the limit is beyond which the code becomes unreadable.

How it works and why. A mapped type walks over keys and builds a new type: { [K in keyof T]: … }. This is how Partial, Readonly and Record are made. Modifiers change properties: ? adds and -? removes optionality, readonly and -readonly do the same for immutability. A mapped type over keyof T keeps the modifiers of the source type, so its "homomorphism" gives a predictable result. Since TypeScript 4.1 keys can be renamed with as.

type Nullable<T> = { [K in keyof T]: T[K] | null };
type Concrete<T> = { [K in keyof T]-?: T[K] };
type Mutable<T> = { -readonly [K in keyof T]: T[K] };

A conditional type is an "if" at the type level: T extends U ? X : Y. Together with infer it extracts part of a type: "substitute whatever is there". The key property is called distributivity: if T is a "naked" type parameter and a union is passed, the condition is applied to each member separately and the results are gathered into a union. This is how Exclude and Extract work.

Distribution over a union

ToArray<string | number>input: a union of two membersstring[] number[]the condition applied to each memberstring[] | number[]result: a union of arrays
Figure 1. The condition checks each union member separately, so ToArray gives a union of arrays, not an array of a union.

Example: two descriptions that drift. A model and a hand-written interface:

interface Balance {
  available: number;
  blocked: number;
  holds: number;
}

interface BalanceApi {
  getAvailable(): Promise<number>;
  getBlocked(): Promise<number>;
}

The method getHolds is missing and nothing demands it. The interface that was supposed to be a "mirror" of the model became a second source of truth.

The fix: derive the client type from the model with a mapped type that renames keys.

type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => Promise<T[K]>;
};

type BalanceApi = Getters<Balance>;

function makeBalanceApi(id: string): BalanceApi {
  return {
    getAvailable: () => fetchField(id, 'available'),
    getBlocked: () => fetchField(id, 'blocked'),
    getHolds: () => fetchField(id, 'holds'),
  };
}

Here keyof T as … renames the key available to getAvailable (the template and Capitalize are covered in the lesson on template literal types), and the value becomes a function returning a promise of the field type. If another field is added to Balance, makeBalanceApi stops compiling until the method appears. The same happens if a method is removed.

Extracting a type with infer. A conditional type is needed when one type depends on another:

type ApiResult<D> =
  | { status: 'success'; data: D }
  | { status: 'error'; message: string };

type DataOf<T> = T extends { status: 'success'; data: infer D } ? D : never;
type ItemOf<T> = T extends readonly (infer I)[] ? I : never;

type A = DataOf<ApiResult<Account>>; // Account
type B = ItemOf<Transaction[]>; // Transaction

DataOf distributes over the union ApiResult: for the success member it returns data, for error it returns never, which vanishes from the union. The result is a clean Account.

T extends U and [T] extends [U]

Distributive

T extends U ? …

A naked parameter: each union member is checked separately. For never the result is never.

Non-distributive

[T] extends [U] ? …

The parameter in a tuple: the union is considered whole. For never the condition holds.

Figure 2. Both are needed: the first for filtering and mapping, the second for checking a union as a whole.

How to switch distribution off and why it sometimes matters:

type ToArray<T> = T extends unknown ? T[] : never;
type R1 = ToArray<string | number>; // string[] | number[]

type ToArrayWhole<T> = [T] extends [unknown] ? T[] : never;
type R2 = ToArrayWhole<string | number>; // (string | number)[]

type IsNeverBad<T> = T extends never ? true : false; // gives never for never
type IsNever<T> = [T] extends [never] ? true : false; // gives true for never

The check for never is telling: never is an empty union, so a distributive condition has nobody to check and returns never, while the tuple wrapper gives the expected true.

Limits and alternatives.

  • In tests such types are written rarely. They are needed in the framework layer: a typed API client, factory generators, wrappers. In a test, simpler types are better.
  • A complex type gives complex error messages. If a colleague cannot read a type, it is simplified or given a name with a comment.
  • Deep recursion in types has a limit, and large unions slow the compiler: a nice idea of a five-level DeepPartial can hit build time.
  • When the shape is known in advance, it is sometimes simpler to write an interface by hand or generate it from OpenAPI than to build it in types.

Common mistakes.

  • Mixing up distributive and non-distributive conditions: IsNever<never> without a tuple gives never.
  • Mapping over keyof T when a list of keys without modifiers is needed: a homomorphic mapped type keeps ? and readonly.
  • Over-complicating types in tests where an interface would do.
  • Renaming keys with as without string & K: keys may be numbers or symbols.

Check yourself

A holds field was added to Balance. Why does BalanceApi = Getters<Balance> force a method to be added while a hand-written interface does not?

Answer

The mapped type builds keys from keyof Balance, so the type of the new method appears at once and an implementation without it does not build. A hand-written interface is not linked to the model, so nobody checks the drift.

Why does type IsNever<T> = T extends never ? true : false give never for IsNever<never>, and how is it fixed?

Answer

The condition is distributive and never is an empty union: there is nobody to check, so the result is never. Wrap both sides in a tuple: [T] extends [never] ? true : false.

In an interview. Junior: A mapped type walks over the keys of keyof T and builds a new type, which is how Partial and Readonly are made. A conditional type is a condition at the type level, and with infer you can extract, for example, the element type of an array. Middle/Senior: I know about distributivity ([T] extends [U] switches it off) and use all this sparingly, mostly in the library layer: a typed client, factories. A complex type that a colleague cannot read I simplify.

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, so the params object is empty.

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.