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.

More articles in this chapter