Intermediate · 14 min
Keys and safe property access
Use keyof to limit a key to the properties of a particular object.
Derive the allowed keys
keyof produces a union of property names for an object type. A string is too broad when only a small set of keys is valid. Keep the key tied to the object type instead of asserting that an arbitrary string is safe.
type Profile = { name: string; points: number };
const key: keyof Profile = "points";
const profile: Profile = { name: "Ada", points: 6 };
console.log(profile[key]);Output
6
Connect a key to its result
A second type parameter constrained by "keyof T" lets a helper accept only keys from its input. The return type T[K] preserves the type of the selected property rather than mixing every property type together.
function get<T, K extends keyof T>(item: T, key: K): T[K] {
return item[key];
}
const city = get({ city: "Lima", visits: 2 }, "city");
console.log(city.toUpperCase());Output
LIMA
Put it into practice
- Read the types and predict the output before running the examples.
- Fix the task without using "any" or a type assertion, then check both practice questions.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Choose an existing key
Fix the call to "get" to read the "city" property. Keep the helper and object unchanged.
The key must belong to the object passed as the first argument.
Show solution
function get<T, K extends keyof T>(item: T, key: K): T[K] { return item[key]; }
const place = { city: "Lima", visits: 2 };
const city = get(place, "city");
console.log(city);The corrected key satisfies keyof for this object. The helper returns a string because the selected property is a string.