Sub topic 5
Using One Type Parameter to Constrain Another
This chapter assumes you know basic TypeScript types, interfaces, generic functions, union types, keyof, and indexed access types such as T[K]. The goal is to make two type parameters depend on each other safely.
The relationship between `T` and `K`
A generic function can use one type parameter to describe a value and another to describe one of its keys:
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 name = getProp(user, "name"); // string
const active = getProp(user, "active"); // boolean
const id = getProp(user, "id"); // numberHere, T represents the type of obj. For user, TypeScript infers:
type User = {
id: number;
name: string;
active: boolean;
};The expression keyof T means “the union of all property names of T.” Therefore, K extends keyof T means that K must be one of those property names.
The return type T[K] is an indexed access type. It means “the type of the property selected by K.” Because K depends on T, the return type follows the key:
const userName = getProp(user, "name"); // string
const userId = getProp(user, "id"); // numberThe compiler rejects keys that are not present:
// getProp(user, "email");
// Error: "email" is not assignable to "id" | "name" | "active"Without the constraint on K, the function could accept any string, and obj[key] would not be safe.
How inference connects the parameters
TypeScript usually infers T from the first argument. It then uses that type to determine the valid choices for K.
function read<T, K extends keyof T>(value: T, key: K): T[K] {
return value[key];
}
const settings = {
theme: "dark",
retries: 3
};
const theme = read(settings, "theme"); // string
const retries = read(settings, "retries"); // numberThe compiler effectively performs these steps:
- Infer
Tas the type ofsettings. - Calculate
keyof Tas"theme" | "retries". - Check that
"theme"is an allowedK. - Return
T[K], which isstringfor that call.
This connection is useful when an output type must reflect a particular input property instead of becoming a broad union.
function pickValue<T, K extends keyof T>(object: T, key: K): T[K] {
return object[key];
}
const record = {
title: "Generic functions",
pages: 240
};
const title = pickValue(record, "title"); // string
const pages = pickValue(record, "pages"); // numberIf the key is stored in a variable, its type affects the result:
const key: keyof typeof record = Math.random() > 0.5 ? "title" : "pages";
const value = pickValue(record, key); // string | numberThe compiler cannot know which property the variable contains at runtime, so it returns the union of both possible property types.
Constraining two values to the same key
A dependent constraint can also ensure that two arguments use the same property key:
function copyProperty<T, K extends keyof T>(
source: T,
target: T,
key: K
): void {
target[key] = source[key];
}
const first = { name: "Ada", age: 36 };
const second = { name: "Grace", age: 28 };
copyProperty(first, second, "name");
copyProperty(first, second, "age");Both objects must have compatible types because they use the same T. The key must belong to that shared type.
When objects have different types, use separate object parameters and constrain the key by both objects:
function copyMatchingProperty<
A,
B,
K extends keyof A & keyof B
>(source: A, target: B, key: K): void {
target[key] = source[key] as B[K];
}
const source = { name: "Ada", id: 1 };
const target = { name: "Unknown", active: false };
copyMatchingProperty(source, target, "name");
// copyMatchingProperty(source, target, "id"); // Errorkeyof A & keyof B contains only keys shared by both types. The assignment may still require an assertion when the property value types are not known to match. A shared key does not automatically mean a shared value type.
> callout note > K extends keyof T constrains the key, but it does not guarantee that two different objects have compatible value types at that key.
Common errors
A frequent mistake is widening a key before calling the function:
const property = "name";
const result = getProp(user, property); // stringIn this example, TypeScript often preserves the literal type "name". But an explicitly broad annotation loses that precision:
const property: string = "name";
// getProp(user, property); // Error: string is not constrained to keyof UserUse keyof typeof user when a variable should hold only valid keys:
const validProperty: keyof typeof user = "name";
const result = getProp(user, validProperty); // string | number | booleanThe result is a union because validProperty could refer to any user property.
Exercise
What is the return type of getProp({ id: 1, label: "x" }, "label"), and why?
Show answer
The return type is string. T is the object type, K is "label", and T[K] selects the type of the label property.