Sub topic 10
`keyof` and Indexed Access Types
Prerequisites
This chapter assumes that you know TypeScript interfaces, type aliases, union types, string literal types, and generic syntax such as Array<T>. You should also understand that a type describes values at compile time, while JavaScript runs at runtime.
Utility types often need to inspect an existing object type. Two important tools make this possible:
keyofproduces a union of an object's property keys.- Indexed access types look up the type of a property by using
T[K].
Using `keyof` to get property names
Given an interface, keyof creates a union containing its keys:
interface User {
id: number;
name: string;
email: string;
}
type UserKey = keyof User;
// "id" | "name" | "email"
const key: UserKey = "name";
// const badKey: UserKey = "age"; // ErrorUserKey is not the same as string. It accepts only keys that exist on User. If you later add or remove a property from User, the keyof result changes automatically.
This is useful when a function should accept a property name and remain synchronized with an object type.
Indexed access types
An indexed access type uses bracket notation at the type level:
type UserName = User["name"];
// string
type UserIdOrName = User["id" | "name"];
// number | string
type AnyUserProperty = User[keyof User];
// number | stringThe expression User["name"] means “the type of the name property in User.” When the index is a union, TypeScript returns a union of the corresponding property types.
At runtime, the equivalent operation is ordinary property access:
const user: User = {
id: 1,
name: "Ada",
email: "[email protected]",
};
const value = user["name"];The type system can connect the key to the returned value with a generic constraint.
Safe generic property access
A generic parameter is a type parameter that lets a function work with several related types. Constrain the key parameter with keyof T:
function getProperty<T, K extends keyof T>(object: T, key: K): T[K] {
return object[key];
}
const user: User = {
id: 1,
name: "Ada",
email: "[email protected]",
};
const name = getProperty(user, "name");
// string
const id = getProperty(user, "id");
// number
// getProperty(user, "age"); // Error: "age" is not a key of UserK extends keyof T says that K must be one of the keys of T. The return type T[K] then preserves the relationship between the argument and the result. Asking for "name" returns string; asking for "id" returns number.
Without this relationship, a function might return an overly broad type such as User[keyof User], which would be number | string.
Arrays and tuples
keyof also works with arrays and tuples, although the result includes methods and numeric-related keys:
type Scores = number[];
type ScoreValue = Scores[number];
// number
type Pair = [string, number];
type PairValue = Pair[number];
// string | numberThe type Scores[number] means “the type of an array element.” For a tuple, indexing with number produces a union of all element types. Indexing with a specific numeric literal selects one position:
type First = Pair[0];
// string
type Second = Pair[1];
// numberHow utility types use these tools
Many utility types are built from keyof and indexed access types. For example, Pick<T, K> keeps selected keys:
type PickedUser = {
[P in "id" | "name"]: User[P];
};
// { id: number; name: string }Here, P iterates over a key union, and User[P] retrieves each property's type. This pattern is called a mapped type and forms the basis of several built-in utility types.
Common errors
keyof uses the declared type, not necessarily the keys currently present in a value. Also, a broad string key is not assignable to keyof User, because most strings are not valid User keys.
When indexing with a generic key, use K extends keyof T. Using an unconstrained K can produce an error because TypeScript cannot prove that the key exists.
Exercise
What is the return type of getProperty(user, "email") when user has type User and email is a string property?
Show answer
The return type is string, because K is inferred as "email" and T[K] is User["email"].