Sub topic 10
keyof and indexed access types
This chapter assumes you can read basic TypeScript: interfaces, type aliases, union and string literal types, and generics such as Array<T>. It covers the two type operators that every utility type is built from. Once you understand keyof and indexed access types, the mapped types in the next chapter are easy to read.
Why these two operators matter
Utility types such as Pick<T, K> and Record<K, V> need to answer two questions about an object type:
- Which property names does this type have?
- What type does a given property have?
keyof answers the first question. An indexed access type, written T[K], answers the second. Both work on types, not on values. They are erased at compile time and produce no JavaScript.
keyof: the keys of a type
keyof T produces a union of the property names of T. Each name becomes a string literal type.
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: Type '"age"' is not assignable to type 'keyof User'.Optional properties are included. Optionality describes the value of a property, not whether its name is a key.
Because the result is an ordinary union, you can use everything you know about unions on it, including Exclude and Extract:
interface User {
id: number;
name: string;
email?: string;
}
type EditableKey = Exclude<keyof User, "id">; // "name" | "email"This is exactly how Omit is defined, as the custom utilities chapter shows.
keyof with other types
keyof is not limited to interfaces. Its result depends on the shape it is given.
| Type | Result of `keyof` | Column | Column |
|---|---|---|---|
| `{ a: 1; b: 2 }` | `"a" \ | "b"` | |
| `{ [k: string]: boolean }` | `string \ | number` | |
| `{ [k: number]: boolean }` | `number` | ||
| `string[]` | `number` plus the array method names such as `"length"` | ||
| `never` | `string \ | number \ | symbol` |
Two rows deserve explanation.
- A type with a string index signature has
string | numberas its keys. JavaScript converts numeric keys to strings, soobj[0]is valid on such a type. keyofon a union type gives only the keys that every member shares. A key must exist on all members to be safe to read.
type Cat = { name: string; meows: boolean };
type Dog = { name: string; barks: boolean };
type PetKey = keyof (Cat | Dog); // "name"
type AnyPetKey = keyof (Cat & Dog); // "name" | "meows" | "barks"Remember the pairing: keyof of a union is the intersection of the key sets, and keyof of an intersection is the union of the key sets. It feels backwards at first, but it follows from what each type allows you to do safely.
keyof typeof: the keys of a value
keyof takes a type. If you have a runtime object and want its keys as a type, first use typeof to get the object's type.
const colors = {
red: "#ff0000",
green: "#00ff00",
blue: "#0000ff",
};
type ColorName = keyof typeof colors; // "red" | "green" | "blue"
function hex(name: ColorName): string {
return colors[name];
}
console.log(hex("green"));This keeps one source of truth. Add a color to the object and ColorName updates by itself. Writing keyof colors without typeof is an error, because colors is a value and keyof needs a type.
Indexed access types: the type of a property
T[K] looks up the type of property K in T. It uses the same bracket syntax as a value lookup, but at the type level.
interface User {
id: number;
name: string;
email?: string;
}
type IdType = User["id"]; // number
type NameType = User["name"]; // string
type EmailType = User["email"]; // string | undefinedNote that User["email"] includes undefined. The optional modifier adds undefined to the property's type, and the lookup returns it. This detail matters when you build utility types, because Required has to remove it.
Indexed access types save you from duplicating a type that already exists. If a function accepts a user's id, derive its parameter type from User instead of writing number again. When the id type later changes to string, the function follows.
interface User {
id: number;
name: string;
}
function findUser(id: User["id"]): User | undefined {
return id > 0 ? { id, name: "Ada" } : undefined;
}
console.log(findUser(1));Looking up several keys at once
The index can be a union. The result is the union of the property types.
interface User {
id: number;
name: string;
email?: string;
}
type IdOrName = User["id" | "name"]; // number | string
type AnyValue = User[keyof User]; // string | number | undefinedT[keyof T] is a common idiom. It means "every value type in T". Mapped types use it often.
Indexing arrays and tuples
Arrays have a numeric index, so number works as the key and returns the element 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 literals instead of string[]. Indexing it with number yields the union of all elements. This is a standard way to define a union type and a runtime list from a single declaration. The parentheses around typeof roles are required by the type grammar when you index the result.
Tuples also accept literal positions:
type Pair = [string, number];
type First = Pair[0]; // string
type Second = Pair[1]; // number
// type Third = Pair[2]; // Error: Tuple type '[string, number]' of length '2' has no element at index '2'.Nested lookups
You can chain lookups to reach into nested types.
interface Settings {
theme: { color: string; size: number };
tags: string[];
}
type Theme = Settings["theme"]; // { color: string; size: number }
type ThemeColor = Settings["theme"]["color"]; // string
type Tag = Settings["tags"][number]; // stringConstraining a generic with keyof
The most useful combination appears in generic functions. You want a function that takes an object and a key, and returns the right type for that key. A constraint of K extends keyof T ensures the key exists, and T[K] gives the exact return type.
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ada", active: true };
const id = getProp(user, "id"); // number
const name = getProp(user, "name"); // string
// getProp(user, "age"); // Error: Argument of type '"age"' is not assignable to parameter of type '"id" | "name" | "active"'.
console.log(id, name);Each call returns a different type, chosen by the key you pass. Without T[K], the best you could write is a return type of unknown or a union of all property types.
This is the same constraint you saw in Pick<T, K extends keyof T>. Pick only accepts keys that exist on T, which is why Pick<User, "age"> fails to compile.
Edge cases and common errors
Using a value as an index
A type position needs a type. This fails:
const field = "name";
interface User {
name: string;
}
// type T = User[field]; // Error: 'field' refers to a value, but is being used as a type here.
type T = User[typeof field]; // stringUse typeof field to turn the value into a type. This works because const field = "name" has the literal type "name". With let field = "name" the type widens to string, and User[string] is an error.
Indexing with a key that does not exist
User["age"] is a compile error, not undefined. Type-level lookups are checked strictly. The one exception is a type with an index signature, where any string key is allowed:
type Dict = { [key: string]: number };
type Value = Dict["anything"]; // numberBe aware that this reports number even though a real lookup of a missing key returns undefined. The compiler does not add undefined unless the noUncheckedIndexedAccess option is on, and that option applies to expressions, not to this type-level lookup.
Optional properties and undefined
Remember that T["optionalKey"] includes undefined. If you want the type without it, wrap the lookup in NonNullable, or use Exclude<T["email"], undefined>.
interface User {
email?: string;
}
type Email = NonNullable<User["email"]>; // stringkeyof returns more than strings
Object keys can be string, number or symbol, so keyof T is typed as string | number | symbol in the general case. If you build a template literal type or call a string method on a key, you may need to narrow it with Extract<keyof T, string>.
interface User {
id: number;
name: string;
}
type StringKey = Extract<keyof User, string>; // "id" | "name"
type Getter = `get${Capitalize<StringKey>}`; // "getId" | "getName"Where this leads
You now have both parts of a mapped type. The next chapter combines them: [K in keyof T] loops over the keys, and T[K] supplies each property's type. Every utility type that reshapes an object, including Partial, Pick and Record, is a variation on that pattern.
Exercise
Given const sizes = { small: 10, medium: 20, large: 30 };, write two types: SizeName, the union of the keys, and SizeValue, the union of the value types. Then write a generic function lookup that takes obj and a key and returns the value with the precise type for that key.
Show answer
type SizeName = keyof typeof sizes; gives "small" | "medium" | "large". type SizeValue = (typeof sizes)[SizeName]; gives number, because the properties are typed as number, not as literals, in a plain object. The function is function lookup<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }. Calling lookup(sizes, "small") returns number, and lookup(sizes, "tiny") is a compile error because "tiny" is not in keyof typeof sizes.
Exercise
What are the types of keyof (A | B) and keyof (A & B) when A = { x: 1; y: 2 } and B = { y: 2; z: 3 }, and why do they differ?
Show answer
keyof (A | B) is "y", and keyof (A & B) is "x" | "y" | "z". A value of type A | B might be either member, so only a key present on both is safe to read. A value of type A & B has all properties of both, so every key from either is available.