Sub topic 5
Using one type parameter to constrain another
This chapter assumes you can write simple generic functions such as identity<T>(x: T): T. It also assumes you know extends constraints on a single type parameter, and that you have seen keyof and indexed access types (T[K]). Here the constraint on one type parameter refers to another type parameter in the same list. This is how TypeScript describes relationships between arguments, such as "this string must be a key of that object".
Why one parameter is not enough
Take a function that reads a property from an object. With one type parameter you have two bad options.
function getPropLoose<T>(obj: T, key: string) {
// return obj[key]; // Error: no index signature, 'string' cannot index type 'T'
}
function getPropAny(obj: any, key: string): any {
return obj[key]; // compiles, but checks nothing
}The first version does not compile. The second compiles, but a typo in key goes unnoticed and the result is any. You want to say two things. key must be a real property name of obj, and the return type must be the type of that property. Both statements link key to obj, so the type of key needs a type parameter whose constraint mentions the type of obj.
The basic pattern: `K extends keyof T`
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"A call to getProp is checked in three steps:
Tis inferred fromobj. Here it becomes{ id: number; name: string }.Kis inferred fromkey. The literal"name"is a candidate.- TypeScript substitutes
Tinto the constraint ofK. That makes the constraint"id" | "name", and"name"satisfies it.
The return type T[K] is then string. If the check in step 3 fails, you get an error on the key argument.
Why the literal type survives
You might expect "name" to widen to string, as it does with let s = "name". It does not here. When a type parameter's constraint includes string literal types (as keyof T does), TypeScript keeps the literal as the inferred type. Without that constraint, K would be inferred as string, and T[K] would not compile.
Declaration order does not matter
A constraint may refer to a type parameter declared later in the same list:
function sumBy<T extends Record<K, number>, K extends PropertyKey>(
items: T[],
key: K
): number {
let total = 0;
for (const item of items) {
total += item[key]; // T[K] resolves to number through the constraint
}
return total;
}
const cart = [
{ name: "pen", price: 3, qty: 2 },
{ name: "book", price: 12, qty: 1 },
];
sumBy(cart, "price"); // OK: price is a number
sumBy(cart, "qty"); // OK
// sumBy(cart, "name"); // Error: string is not assignable to numberIn this example the dependency runs the other way. K is inferred from the string you pass. T must then have a numeric property under that key. The error for "name" appears because { name: string; price: number; qty: number } does not satisfy Record<"name", number>.
This is why keyof T is not the only useful pattern. Whenever a relationship between two arguments is the thing you want to enforce, make one parameter's constraint mention the other.
Tying a value to a key
The same technique ties a value's type to a key:
function setProp<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
obj[key] = value;
}
const account = { id: 1, name: "Ada" };
setProp(account, "name", "Grace"); // OK
// setProp(account, "name", 42); // Error: number is not assignable to string
// setProp(account, "id", "x"); // Error: string is not assignable to numbervalue: T[K] is not a place where TypeScript infers T. T comes from obj and K from key. The value parameter is only checked against the type that those two produce. This is the behavior you want. The key decides the type, and the value has to agree.
Returning a subset: `Pick<T, K>`
Constraints between parameters also let the return type depend on which keys were requested:
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 person = { id: 7, name: "Ada", email: "[email protected]" };
const idOnly = pick(person, ["id"]); // Pick<..., "id">
const contact = pick(person, ["name", "email"]); // Pick<..., "name" | "email">
contact.email; // OK
// contact.id; // Error: property 'id' does not exist on the picked typeWith keys: K[], TypeScript infers K as the union of all the literals in the array. The result type therefore contains exactly the properties you asked for. The cast {} as Pick<T, K> is needed because an empty object does not yet have those properties. The loop fills them in.
Constraining one parameter by "is a kind of"
A constraint can also state that one parameter must be a subtype of another:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark(): string {
return "woof";
}
}
function upcast<Sub extends Base, Base>(items: Sub[]): Base[] {
return items; // OK: Sub is assignable to Base, and arrays are covariant here
}
const dogs: Dog[] = [new Dog()];
const animals = upcast<Dog, Animal>(dogs); // Animal[]
const unknowns = upcast(dogs); // unknown[]: Base had no inference candidatesThe last line shows an inference limit. Base appears only in the constraint of Sub, and TypeScript does not infer a type parameter from another parameter's constraint. With no candidates, Base becomes unknown. That is legal, because every Sub extends unknown, so you get no error and lose the information you wanted. When a parameter has no inference site in the arguments, either give it one or pass the type arguments explicitly.
What `keyof T` contains
The constraint K extends keyof T is only as precise as keyof T. Three cases catch people out.
| `T` | `keyof T` | Consequence for `K` | Column |
|---|---|---|---|
| `{ id: number; name: string }` | `"id" \ | "name"` | Only those two literals are accepted. |
| `{ [k: string]: number }` | `string \ | number` | Any string is accepted, and `T[K]` is `number`. |
| `A \ | B` (a union of object types) | Only keys present in both `A` and `B` | A key that exists on just one member is rejected. |
The index signature row matters in practice. If T is a dictionary type, K is no longer a literal, and the constraint cannot catch typos.
keyof T can also be string | number | symbol. If you want to use the key as text, convert it or narrow it:
function labelFor<T, K extends keyof T>(key: K): string {
return `field:${String(key)}`; // template literal needs string; String() accepts symbols
}
function stringKeysOnly<T, K extends Extract<keyof T, string>>(obj: T, key: K): string {
return `${key}=${String(obj[key])}`; // K is always a string here
}Extract<keyof T, string> keeps only the string-named keys. It is the usual way to rule out number and symbol keys.
Common errors
These are the mistakes you are most likely to meet in this area.
- Dropping the constraint on
K.function getProp<T, K>(obj: T, key: K): T[K]fails with "Type 'K' cannot be used to index type 'T'". TypeScript has no proof thatKis a key. - Constraining
keywithstringinstead ofK.key: keyof Taccepts valid keys but loses which key was passed. The return type becomes the union of all property types,T[keyof T]. You need a separateKto remember the specific key. - Expecting inference through a constraint. A parameter used only in another parameter's constraint, like
Baseabove, falls back tounknown. - Passing a widened key. If a key is typed
stringbefore the call, as inconst k: string = "name", the call fails.stringis not assignable tokeyof T. Useas const, a literal type annotation, or akeyoftype for the variable.
const user2 = { id: 1, name: "Ada" };
const wide: string = "name";
// getProp(user2, wide); // Error: string is not assignable to "id" | "name"
const narrow = "name"; // const keeps the literal type "name"
getProp(user2, narrow); // OK
const fromList: (keyof typeof user2)[] = ["id", "name"];
getProp(user2, fromList[0]); // OK: type is "id" | "name", result is string | numberThe last line shows a related effect. When K is the whole union "id" | "name", T[K] is the union of both property types.
Summary of patterns
| Goal | Signature shape | What it enforces |
|---|---|---|
| Read a property | `<T, K extends keyof T>(obj: T, key: K): T[K]` | `key` is a real key, and the result type follows it. |
| Write a property | `<T, K extends keyof T>(obj: T, key: K, value: T[K])` | `value` matches the property type. |
| Select several keys | `<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K>` | The result has exactly the chosen keys. |
| Require a typed field | `<T extends Record<K, number>, K extends PropertyKey>` | `T` has a numeric property under key `K`. |
| Subtype relationship | `<Sub extends Base, Base>` | `Sub` can stand in for `Base`. |
Exercises
Exercise
Write a function pluck that takes an array of objects and a key, and returns an array of that property's values. For pluck([{ id: 1, name: "a" }], "name") the result type must be string[], and pluck(items, "missing") must be a compile error. What is the signature?
Show answer
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] { return items.map(item => item[key]); }. T is inferred from the array elements and K from the key. The constraint rejects keys not in keyof T, and T[K][] gives string[] for the key "name".
Exercise
Why does function f<T, K>(obj: T, key: K): T[K] fail to compile, and what is the smallest change that fixes it?
Show answer
K is unconstrained, so TypeScript cannot guarantee that K is a valid key of T, and T[K] is not allowed. Change the declaration to K extends keyof T. Then K can only be a key of T, and indexing T by K is valid.
Exercise
Given function upcast<Sub extends Base, Base>(items: Sub[]): Base[] and const dogs: Dog[] = [...], what is the type of upcast(dogs), and why does TypeScript not report an error?
Show answer
It is unknown[]. Base appears only in the constraint of Sub, so it has no inference candidates and falls back to unknown. Every Sub satisfies extends unknown, so the call is valid, and you must write upcast<Dog, Animal>(dogs) to get Animal[].