Intermediate · 8 of 16 · 14 min read
keyof and indexed access
Reading keys and property types out of a type instead of writing them again — the two operators every utility type is built from.
- keyof
keyof T gives you the keys of a type as a union. T[K] gives you the type stored under a key.
Together they are how a helper stays correct when the shape it works on changes — and they are the
raw material of every utility type in the standard library.
keyof
interface User {
id: number;
name: string;
}
type UserKey = keyof User; // "id" | "name"
const k: UserKey = "name";
// const bad: UserKey = "email"; // not assignable
console.log(k);
A few results are worth knowing because they are not obvious:
type A = keyof { [k: string]: number }; // string | number
type B = keyof { [k: number]: number }; // number
type C = keyof string[]; // number | "length" | "push" | ... every member
type D = keyof {}; // never
type E = keyof unknown; // never
const c: C = "length";
console.log(c);
keyof on a string index signature includes number, because JavaScript converts numeric keys to
strings. And keyof on an array gives you every array method name as well as number — which is
why you rarely want it there.
Indexed access
interface User {
id: number;
name: string;
tags: string[];
address: { city: string };
}
type Name = User["name"]; // string
type IdOrName = User["id" | "name"]; // number | string
type Tag = User["tags"][number]; // string
type City = User["address"]["city"]; // string
const t: Tag = "x";
console.log(t);
The key has to be a type, not a value — User[key] with a const key = "name" is an error,
and User[typeof key] is what you meant. Indexing with a union gives the union of those property
types, and [number] on an array or tuple gives the element type.
const roles = ["admin", "user"] as const;
type Role = (typeof roles)[number]; // "admin" | "user"
type Pair = [string, number];
type First = Pair[0]; // string
type Either = Pair[number]; // string | number
const r: Role = "admin";
console.log(r);
That (typeof arr)[number] idiom is the most useful thing on this page: one as const array
gives you both the runtime list and the type, with nothing to keep in sync.
The type-safe getter
The canonical use, and a common interview exercise:
function get<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ana", active: true };
const id = get(user, "id"); // number
const name = get(user, "name"); // string
const active = get(user, "active"); // boolean
// get(user, "email"); // not assignable to '"id" | "name" | "active"'
console.log(id.toFixed(0), name.toUpperCase(), active);
Two type parameters tied together: T is the object, K is constrained to its keys, and the
return T[K] is read from both. Without the constraint, obj[key] would not even compile.
The same shape works for a setter, and for a pick:
function set<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
obj[key] = value;
}
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
const users = [{ id: 1, name: "Ana" }, { id: 2, name: "Beto" }];
console.log(pluck(users, "name")); // ["Ana", "Beto"] — typed string[]
Indexing an object with a plain string
A frequent error, and the fix is the same constraint:
const config = { host: "localhost", port: 8080 };
// function readBad(key: string) {
// return config[key]; // implicitly has an 'any' type
// }
function read<K extends keyof typeof config>(key: K): (typeof config)[K] {
return config[key];
}
console.log(read("host").toUpperCase()); // "LOCALHOST"
console.log(read("port").toFixed(0)); // "8080"
// read("missing"); // not assignable
string is wider than the object’s keys, so the compiler has no element type to give you. The
constraint narrows the key and the return type follows from it.
Filtering keys by their value type
Once you have keyof, you can select from it:
interface User {
id: number;
name: string;
age: number;
}
type KeysOfType<T, V> = {
[K in keyof T]: T[K] extends V ? K : never;
}[keyof T];
type NumberKeys = KeysOfType<User, number>; // "id" | "age"
type StringKeys = KeysOfType<User, string>; // "name"
const n: NumberKeys = "age";
console.log(n);
The trick in the middle is worth reading twice: a mapped type assigns each key either itself or
never, and then indexing the whole thing with [keyof T] collapses it to the union of the
values — and never disappears from a union, so the unwanted keys drop out.
keyof typeof
For a value rather than a type, typeof lifts it into the type world first:
const PERMISSIONS = {
read: 1,
write: 2,
admin: 4,
} as const;
type Permission = keyof typeof PERMISSIONS; // "read" | "write" | "admin"
type Level = (typeof PERMISSIONS)[Permission]; // 1 | 2 | 4
function allow(permission: Permission): Level {
return PERMISSIONS[permission];
}
console.log(allow("admin")); // 4
One declaration, two derived types, and adding a permission updates both.
Where the utility types come from
Nearly all of them are keyof plus a mapped type:
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
type MyRecord<K extends PropertyKey, V> = { [P in K]: V };
interface User { id: number; name: string }
type A = MyPick<User, "id">; // { id: number }
const a: A = { id: 1 };
console.log(a.id);
Knowing that is the difference between using the utility types and being able to write the one the standard library is missing.
Common mistakes
Expecting keyof to give the value types
Mistake. Reading keyof User as number | string.
Why it fails. It is the union of key names — "id" | "name". The value types come from
T[keyof T].
What to do instead. keyof T for names, T[keyof T] for the union of value types.
Indexing a type with a value
Mistake. const key = "name"; type N = User[key];
Why it fails. The index has to be a type. key is a value.
What to do instead. User[typeof key], or just User["name"].
Taking a string key parameter
Mistake. function get(obj: Config, key: string).
Why it fails. string is wider than the object’s keys, so the lookup is an implicit any
and a typo at the call site is never caught.
What to do instead. K extends keyof T, returning T[K].
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
keyof turns the keys of a type into a union of literal types.
What is keyof User here?
interface User {
id: number;
name: string;
}What does an indexed access type User["name"] give you?
Indexing an object with a plain string is not the same as indexing it with one of its keys.
Why does this fail under noImplicitAny?
const config = { host: "localhost", port: 8080 };
function read(key: string) {
return config[key];
}Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.