Sub topic 4
Constraining keys with keyof
This chapter assumes you can write simple generic functions, know extends constraints from the previous chapters, and have seen keyof and indexed access types (T[K]). Here you will combine them. The pattern K extends keyof T is the most common way to make one type parameter depend on another, and it appears in many libraries.
The problem: keys typed as plain strings
Suppose you want a function that reads a property by name. The first attempt types the key as string:
function getLoose<T>(obj: T, key: string) {
return obj[key]; // Error under "strict": 'string' cannot be used to index type 'T'
}The compiler rejects this because nothing says key names a property of obj. Silencing the error with any would compile, but the function would return any and accept typos such as "nmae".
You need two guarantees:
- The key must be an actual property name of the object.
- The return type must be the type of that specific property, not a union of all property types.
keyof and indexed access give you both.
A quick recap of keyof and T[K]
keyof T produces a union of the known property names of T, as string, number, or symbol literal types. T[K] is the type of the property K in T.
interface User {
id: number;
name: string;
}
type UserKeys = keyof User; // "id" | "name"
type NameType = User["name"]; // string
type AnyValue = User[keyof User]; // number | stringThe last line shows why a bare keyof is not enough on its own. If you index with the whole union, you get the union of all value types.
The K extends keyof T pattern
Making K a second type parameter, constrained by keyof T, solves both problems:
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ada" };
const name = getProp(user, "name"); // type: string
const id = getProp(user, "id"); // type: number
// getProp(user, "email"); // Error: "email" is not assignable to "id" | "name"Each part has a job:
Tis inferred fromobj. Here it is{ id: number; name: string }.K extends keyof Tlimitskeyto the names in that type. An unknown name is an error at the call site.T[K]is the return type. BecauseKis a specific literal such as"name", the result isstring, notstring | number.- Inside the body,
obj[key]is allowed. TypeScript knowsKis a valid key ofT.
Why K is inferred as a literal
Normally a string argument widens: const x = f("name") with f<T>(v: T) infers T as string in some positions. When the constraint of a type parameter includes string literal types (as keyof T does), TypeScript keeps the literal. So K becomes "name", not string. This is why the return type is precise.
The order of inference matters too. TypeScript infers T from obj and K from key, then checks K against keyof T. The checks happen after both candidates are collected, so the order of the parameters does not matter for correctness. You can put the key first if the API reads better that way.
What happens with a union-typed key
The key argument does not have to be a literal. If it is a union of keys, K becomes that union and T[K] becomes a union of the matching property types:
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ada" };
declare const field: "id" | "name";
const value = getProp(user, field); // type: string | numberThis is correct but less precise. TypeScript cannot know which of the two keys field holds at runtime, so it reports both possibilities.
Writing to a property
The same constraint makes a type-safe setter. The new value must match the type of the chosen property:
function setProp<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
obj[key] = value;
}
const user = { id: 1, name: "Ada" };
setProp(user, "name", "Grace"); // OK
// setProp(user, "name", 42); // Error: number is not assignable to string
// setProp(user, "id", "x"); // Error: string is not assignable to numberHere K ties two parameters together. key selects a property and value must have that property's type. A signature that took value: unknown or value: T[keyof T] would let you assign a string to id.
Selecting several keys
A key list is also constrained by keyof T. Typing the array element as K lets TypeScript collect all the literal keys into one union:
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 user = { id: 1, name: "Ada", email: "[email protected]" };
const slim = pick(user, ["id", "name"]);
// type: Pick<{ id: number; name: string; email: string }, "id" | "name">
console.log(slim.name); // "Ada"
// console.log(slim.email); // Error: 'email' does not exist on the picked typeFor the array ["id", "name"], K is inferred as "id" | "name". Pick<T, K> is a built-in mapped type that keeps only those properties. The {} as Pick<T, K> assertion is needed because an empty object literal is not yet a full Pick. This is a place where a small, contained assertion is reasonable, since the loop fills in exactly the keys the type promises.
What keyof actually returns: edge cases
keyof T is not always the list of names you see in the source. These cases surprise people:
| Type | `keyof` result | Note | Column | Column | Column |
|---|---|---|---|---|---|
| `{ id: number; name: string }` | `"id" \ | "name"` | The common case. | ||
| `{ [k: string]: number }` | `string \ | number` | Numeric keys are also valid on a string index signature. | ||
| `{ [k: number]: string }` | `number` | A number index signature gives only `number`. | |||
| `A \ | B` (union of objects) | Only the keys common to both | You can only safely read what every member has. | ||
| `A & B` (intersection) | The keys of either | The combined object has all of them. | |||
| `string[]` | `number \ | "length" \ | "push" \ | ...` | Includes every array method name. |
Three practical consequences follow.
First, with an index signature, K extends keyof T accepts any string, so you lose the typo protection. The constraint is only as strict as the type you pass in.
Second, for a union of objects, getProp only accepts the shared keys:
type Cat = { kind: "cat"; lives: number };
type Dog = { kind: "dog"; breed: string };
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
declare const pet: Cat | Dog;
const kind = getProp(pet, "kind"); // type: "cat" | "dog"
// getProp(pet, "lives"); // Error: "lives" is not a key of Cat | DogThird, optional properties flow through T[K] with undefined included:
interface Settings {
theme?: string;
fontSize: number;
}
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
declare const settings: Settings;
const theme = getProp(settings, "theme"); // type: string | undefinedUnder exactOptionalPropertyTypes the result may differ slightly, but undefined is still part of what you must handle.
Keys that are not strings
keyof T can include number and symbol. That matters if you use a key in a string-only context, such as a template literal or string method:
function logKey<T, K extends keyof T>(key: K): void {
// console.log(key.toUpperCase()); // Error: K could be a number or symbol
console.log(String(key));
}When you need string keys only, narrow the constraint with Extract:
function listKeys<T extends object>(obj: T): Extract<keyof T, string>[] {
return Object.keys(obj) as Extract<keyof T, string>[];
}
const keys = listKeys({ id: 1, name: "Ada" }); // type: ("id" | "name")[]The assertion is needed because Object.keys returns string[]. A value can have more properties at runtime than its static type declares, so TypeScript does not trust the result. This is the same reason for...in and Object.keys do not give you keyof T automatically.
Common errors
- Using
keyof Tdirectly instead ofK. Writingkey: keyof Taccepts valid keys, but the return type becomesT[keyof T], the union of all value types. Add the second parameterKto get precision. - Forgetting that the constraint is checked, not used for inference. TypeScript infers
Kfrom thekeyargument. It does not pick a key for you. If the argument is a widenedstringvariable, the call fails. - Widening through
letor a mutable object.let k = "name"has typestring, sogetProp(user, k)fails. Useconst k = "name"or annotatekwith a key union. - Assuming a key that exists at runtime exists in the type.
keyofonly knows what the static type says.
Why a second parameter and not one
You might wonder whether a single type parameter could do the job, for example function get<K extends string>(obj: Record<K, unknown>, key: K). That works for some shapes, but it loses the property types, because values become unknown. Using T for the whole object and K for the key keeps the full structure available, so T[K] can compute the exact type. This dependency of one parameter on another is the idea the next chapter develops in more general form.
Exercises
Exercise
Write a function pluck that takes an array of objects of type T and a key K extends keyof T, and returns an array of the values at that key. What is the return type, and what type does pluck([{ id: 1, name: "Ada" }], "name") have?
Show answer
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] { return items.map((item) => item[key]); }. The return type is T[K][], an array of the property type. The call returns string[], because T is { id: number; name: string } and K is "name".
Exercise
Given function getProp<T, K extends keyof T>(obj: T, key: K): T[K] and declare const pet: { kind: "cat"; lives: number } | { kind: "dog"; breed: string }, which of getProp(pet, "kind") and getProp(pet, "lives") compile, and why?
Show answer
Only getProp(pet, "kind") compiles, with type "cat" | "dog". keyof applied to a union of object types gives only the keys common to every member. "lives" exists only on the cat type, so it is not in keyof (Cat | Dog) and the call is an error.