Sub topic 7
`keyof` and Indexed Access Types
Prerequisites
This chapter assumes you know object types, interfaces, unions, generic functions, and basic type parameters. You should also be comfortable reading expressions such as User["name"].
keyof and indexed access types let a generic function connect an object to one of its valid property names. This connection prevents invalid keys and preserves the type of the selected property.
Getting the Keys of a Type
The keyof operator produces a union of an object's property names.
interface User {
id: number;
name: string;
active: boolean;
}
type UserKey = keyof User;
// "id" | "name" | "active"UserKey is not the string type. It is a narrower union containing only the keys that exist on User.
| Type expression | Result | Column | Column |
|---|---|---|---|
| `keyof User` | `"id" | "name" | "active"` |
| `User["id"]` | `number` | ||
| `User["name"]` | `string` | ||
| `User[keyof User]` | `number | string | boolean` |
You can use a key union to constrain a value:
function printKey(key: keyof User): void {
console.log(key);
}
printKey("name"); // OK
// printKey("email"); // Error: "email" is not a key of UserIndexed Access Types
An indexed access type reads a property type by using bracket syntax. It resembles reading a property in JavaScript, but it happens at the type level.
type UserName = User["name"]; // string
type UserId = User["id"]; // number
type UserValue = User[keyof User]; // number | string | booleanWhen the index is a union, TypeScript returns a union of the matching property types:
type UserText = User["name" | "active"];
// string | booleanIndexed access also works with arrays and tuples:
type Names = string[];
type Name = Names[number]; // string
type Coordinates = [number, number];
type Coordinate = Coordinates[number]; // numberThe special index number means “any numeric position” in an array or tuple.
Connecting Keys and Values in Generic Code
A useful generic function needs two type parameters:
Trepresents the object.Krepresents one of its keys.
The constraint K extends keyof T guarantees that K is a valid key. The return type T[K] then gives the value type for that particular key.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = {
id: 1,
name: "Ada",
active: true,
};
const name = getProperty(user, "name"); // string
const active = getProperty(user, "active"); // boolean
// getProperty(user, "email"); // ErrorTypeScript infers T as the object type and K as the specific key used at the call site. Because the key is connected to the result, name is a string, not a broad union of every possible user value.
Common Errors
A frequent mistake is to use keyof T as the return type:
function wrong<T>(obj: T, key: keyof T): keyof T {
return obj[key];
}This describes a key, not the value stored at that key. The correct return type is T[typeof key] in a non-generic context, or T[K] when the key has its own type parameter.
Another mistake is using an unconstrained string:
function unsafe<T>(obj: T, key: string) {
// TypeScript cannot prove that key exists on T.
return obj[key as keyof T];
}The type assertion hides the problem instead of preventing it. Prefer K extends keyof T so callers receive an error for invalid keys.
Exercise
For interface Product { sku: string; price: number; }, what are the types of keyof Product and Product["price"]?
Show answer
keyof Product is "sku" | "price", and Product["price"] is number.