Sub topic 4
Constraining Keys with `keyof`
This chapter assumes basic TypeScript types, interfaces, unions, and generic functions. You should also know that keyof produces the property names of an object type, and that indexed access types such as T[K] look up a property type.
Why an unconstrained key is unsafe
Suppose a function receives an object and a property name:
function getValue<T>(object: T, key: string) {
return object[key];
}TypeScript rejects object[key] because T could be any type. A value of type T might be a number, a boolean, or an object with no property matching the string. The compiler cannot prove that the lookup is safe.
We can make the key depend on the object 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 name = getProp(user, "name");
const active = getProp(user, "active");
console.log(name); // Ada
console.log(active); // trueHere, T represents the object type. keyof T is a union of the keys in that type. For the user value, it is equivalent to:
type UserKey = "id" | "name" | "active";K extends keyof T means that K must be one of those keys. The return type T[K] is the type of the selected property. Therefore, getProp(user, "name") returns string, while getProp(user, "id") returns number.
How the two type parameters work together
The type parameters are inferred from the function arguments:
- TypeScript infers
Tfromobj. - It computes
keyof T. - It checks that the supplied key fits that set.
- It uses
T[K]to calculate the return type.
flowchart TD
A["obj: T"] --> B["keyof T"]
B --> C["K must be one of T's keys"]
C --> D["T[K] gives the selected property type"]caption: How keyof connects an object, its keys, and a property value alt: A flowchart showing an object type T producing its keys, which constrain K, which then determines the indexed access type T[K].
An invalid key is caught at the call site:
// getProp(user, "email");
// Error: "email" is not assignable to
// "id" | "name" | "active"This is more useful than accepting string and discovering a missing property only at runtime.
Optional and union properties
T[K] preserves the property type, including undefined when a property is optional.
interface Settings {
theme: "light" | "dark";
language?: string;
}
function readSetting<K extends keyof Settings>(
settings: Settings,
key: K
): Settings[K] {
return settings[key];
}
const settings: Settings = { theme: "dark" };
const theme = readSetting(settings, "theme");
// type: "light" | "dark"
const language = readSetting(settings, "language");
// type: string | undefinedThe compiler does not remove the possibility that language is absent. Your code must handle that possibility before using the value as a definite string.
Common errors
Using `keyof` on the wrong type
The key constraint must describe the object being indexed. This is correct:
function getName<T extends { name: string }>(obj: T): string {
return obj.name;
}For a property selected by the caller, use K extends keyof T, not K extends string. A string constraint allows names that the object does not contain.
Returning the wrong value type
A function that returns T[K] must return the property selected by K:
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}Returning obj.name would not be valid for every possible K, because K might be "id" and the result would then need to be a number.
Confusing keys with values
keyof T describes property names. It does not describe the types of the properties. For this type:
interface Product {
sku: string;
price: number;
}keyof Product is "sku" | "price", while Product[keyof Product] is string | number.
Practice
A reusable helper can use the same relationship to update a property:
function setProp<T, K extends keyof T>(
obj: T,
key: K,
value: T[K]
): void {
obj[key] = value;
}
const profile = {
name: "Ada",
age: 36,
};
setProp(profile, "name", "Grace");
setProp(profile, "age", 37);
console.log(profile);The third parameter depends on the second. A string is accepted for "name", but not for "age".
Exercise
What should the return type be for a generic function that receives obj: T and key: K, where K extends keyof T, and returns obj[key]?
Show answer
The return type should be T[K]. It represents the type of the property selected by K.