Sub topic 7
keyof and Indexed Access Types
This chapter assumes you can write generic functions with extends constraints, read union types, and use object types, interfaces, and type aliases. Here you will learn two type operators that let a generic function talk about the properties of an object type. keyof produces the names of those properties, and indexed access reads the types of their values.
The keyof operator
keyof takes an object type and returns a union of its keys as string or number literal types.
interface User {
id: number;
name: string;
email?: string;
}
type UserKey = keyof User; // "id" | "name" | "email"
const key: UserKey = "name"; // OK
// const bad: UserKey = "age"; // Error: not assignable to type UserKeyThe result is a type, not a runtime value. keyof is erased when the code is compiled, and it works only on types. To get the keys of a value, first take its type with typeof.
const settings = { theme: "dark", fontSize: 14 };
type SettingKey = keyof typeof settings; // "theme" | "fontSize"What keyof returns for other shapes
The result depends on the shape of the type.
| Type | `keyof` result | Column | Column | Column |
|---|---|---|---|---|
| `{ a: 1; b: 2 }` | `"a" \ | "b"` | ||
| `{ [key: string]: boolean }` | `string \ | number` | ||
| `{ [key: number]: boolean }` | `number` | |||
| `string[]` | `number \ | "length" \ | "push" \ | ...` (all array members) |
| `A \ | B` | only the keys common to both | ||
| `A & B` | the keys of either |
Two of these rows surprise people.
- String index signatures. A type with a string index signature accepts numeric keys too, because
obj[0]is treated asobj["0"]. Sokeyofincludesnumber. - Unions and intersections. For a union, only keys that every member has are safe to read, so
keyof (A | B)is the shared keys. An intersection has every key from both sides.
interface Cat { name: string; meows: boolean }
interface Dog { name: string; barks: boolean }
type Shared = keyof (Cat | Dog); // "name"
type All = keyof (Cat & Dog); // "name" | "meows" | "barks"For a class, keyof on the instance type returns only public members. Private and protected members are not included.
Indexed access types
An indexed access type looks up the type of a property. You write it like a property read, but in type position: T[K].
interface User {
id: number;
name: string;
email?: string;
}
type IdType = User["id"]; // number
type NameType = User["name"]; // string
type EmailType = User["email"]; // string | undefinedThe optional property email gives string | undefined, because reading it can return undefined. Remember this when you build generic helpers on top of T[K].
The index can also be a union. TypeScript looks up each member and unions the results.
type IdOrName = User["id" | "name"]; // number | string
type AnyValue = User[keyof User]; // string | number | undefinedUser[keyof User] is a common idiom for "the union of all value types in this object type".
Indexing arrays and tuples
Arrays are indexed by number, so T[number] is the element type. This is the standard way to get an element type from an array type.
type Names = string[];
type Name = Names[number]; // string
const roles = ["admin", "editor", "viewer"] as const;
type Role = (typeof roles)[number]; // "admin" | "editor" | "viewer"The as const assertion makes roles a readonly tuple of literal types. Without it, roles would be string[] and Role would be plain string. Tuples can also be indexed by position:
type Row = [id: number, label: string];
type First = Row[0]; // number
type Second = Row[1]; // string
// type Third = Row[2]; // Error: tuple has no element at index 2A common mistake: using a value as the index
The index in T[K] must be a type. Writing a variable name there does not work, even when the variable holds a string.
interface User {
id: number;
name: string;
}
const field = "name";
// type Bad = User[field]; // Error: 'field' refers to a value, but is used as a type
type Good = User[typeof field]; // stringtypeof field works here because field is a const, so its type is the literal "name". With let field = "name" its type would be string, and User[string] is an error.
Combining them: a type-safe property getter
The two operators work together with a constraint. This is the function from the topic's reference examples.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ada" };
const name = getProperty(user, "name"); // string
const id = getProperty(user, "id"); // number
// getProperty(user, "email"); // Error: not a key of userEach part has a job.
Tis the type of the object, inferred fromuser.K extends keyof Tlimitskeyto names that exist onT. TypeScript infersKas the literal"name", notstring, because the constraint is a union of literals.T[K]ties the return type to the key that was passed. A call with"name"returnsstring, and a call with"id"returnsnumber.
Without the T[K] return type, the function would have to return a union of all value types, and every caller would need to narrow it.
Setting a property safely
The same pattern makes a setter where the value must match the property's type.
function setProperty<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
obj[key] = value;
}
const point = { x: 0, y: 0 };
setProperty(point, "x", 10); // OK
// setProperty(point, "x", "10"); // Error: string is not assignable to numberK appears in both key and value, so TypeScript fixes it from key and then checks value against T[K].
Selecting several keys
To pick several properties, make K stand for a union of keys and take an array of them. The built-in Pick<T, K> type, covered in a later chapter, describes the result.
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
const result = {} as Pick<T, K>;
for (const key of keys) {
result[key] = obj[key];
}
return result;
}
const todo = { title: "Write", done: false, notes: "draft" };
const summary = pick(todo, ["title", "done"]);
// { title: string; done: boolean }The {} as Pick<T, K> assertion is needed because an empty object does not yet have the required properties. It is safe here only because the loop fills in every key before the function returns.
Keys tied to payload types
Indexed access is useful whenever one key decides the type of another argument. An event system is a typical case.
interface EventMap {
click: { x: number; y: number };
keydown: { code: string };
}
function on<K extends keyof EventMap>(
event: K,
handler: (payload: EventMap[K]) => void
): void {
console.log(`registered handler for ${event}`);
}
on("click", (p) => console.log(p.x, p.y)); // p is { x: number; y: number }
on("keydown", (p) => console.log(p.code)); // p is { code: string }
// on("scroll", () => {}); // Error: "scroll" is not a key of EventMapAdding a new event means adding one line to EventMap. Every call to on then accepts the new name and types its payload correctly.
Edge cases and gotchas
keyof can include number and symbol
keyof T is a subtype of string | number | symbol. Index signatures add number, and symbol-keyed properties add symbol. If you build a template literal type from a key, the compiler rejects it until you narrow to strings.
interface Config {
host: string;
port: number;
}
type ChangeEvent<T> = `${Extract<keyof T, string>}Changed`;
type ConfigEvent = ChangeEvent<Config>; // "hostChanged" | "portChanged"Extract<keyof T, string> keeps only the string members of the union. Writing ${keyof T} directly is an error because symbol cannot appear in a template literal type.
Literal keys need const or a literal context
Key inference depends on how the key is written.
| Code | Type of the key | Works with `K extends keyof T`? |
|---|---|---|
| `getProperty(user, "name")` | `"name"` | Yes |
| `const k = "name"` | `"name"` | Yes |
| `let k = "name"` | `string` | No, error at the call |
| `const k: string = "name"` | `string` | No, error at the call |
When a key comes from user input or JSON, it is a plain string. You must check it first. A type guard works well here.
function isKeyOf<T extends object>(obj: T, key: PropertyKey): key is keyof T {
return key in obj;
}
const record = { a: 1, b: 2 };
const input: string = "a";
if (isKeyOf(record, input)) {
const value = record[input]; // number
}The in check is a runtime test, and the key is keyof T return type tells the compiler to trust it. The guard also matches inherited names such as "toString". Use Object.hasOwn(obj, key) instead when inherited properties must not count.
Indexed access on a generic is deferred
Inside a generic function, T[K] stays unresolved until the call site supplies real types. That is why you cannot assign an arbitrary value to obj[key] inside the function. Only a value of type T[K] is accepted, as setProperty shows.
Where this leads
keyof is the input to mapped types. A mapped type iterates over keyof T and uses T[K] for each value, so everything in this chapter appears again in the next chapters. The built-in Pick and Readonly are small definitions built from exactly these two operators.
Exercise
Write a generic function pluck that takes an array of objects and a key, and returns an array of that property's values. For pluck([{ id: 1, name: "Ada" }, { id: 2, name: "Lin" }], "name") the result type must be string[]. Calling it with "email" must be a compile error.
Show answer
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] { return items.map((item) => item[key]); } const people = [{ id: 1, name: "Ada" }, { id: 2, name: "Lin" }]; const names = pluck(people, "name"); // string[] // pluck(people, "email"); // Error: not a key of the element type T is inferred from the element type of the array, K is constrained to its keys, and T[K][] is an array of the looked-up property type.
Exercise
Given const levels = ["low", "medium", "high"] as const;, define a type Level that is the union of its elements. What would Level be if as const were removed?
Show answer
type Level = (typeof levels)[number]; // "low" | "medium" | "high"
Without as const, levels is string[], so Level would be string. The literal types are only kept when the array is declared as a readonly tuple of literals.