Sub topic 8
Type-safe property access with K extends keyof T
This chapter assumes you know TypeScript interfaces, type aliases, union types, and basic generics. It also assumes you have met keyof T and indexed access types like T[K] from the earlier chapters. Here they combine into one pattern: a generic function that accepts only keys that exist on an object and returns the exact type of the property it reads.
The problem: property access by name
JavaScript code often reads a property whose name arrives as an argument. A first attempt in TypeScript usually looks like this:
function getPropertyLoose(obj: any, key: string): any {
return obj[key];
}
const user = { id: 1, name: "Ada" };
const age = getPropertyLoose(user, "age"); // any, no error, undefined at runtimeThis compiles, but it checks nothing. A typo in the key is accepted, and the result is any, so later code gets no help either.
Typing obj precisely does not fix it. If you write obj: object and key: string, the line obj[key] fails under noImplicitAny, because a plain string cannot index an arbitrary object type. TypeScript can only allow the lookup when it knows the key is one of the object's actual property names.
The pattern
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ada" };
const name = getProperty(user, "name"); // type: string
const id = getProperty(user, "id"); // type: number
// getProperty(user, "age"); // Error: "age" is not assignable to "id" | "name"There are three parts to this signature.
Tis the type of the object. TypeScript infers it from the first argument.K extends keyof Tis a second type parameter, constrained to be one ofT's keys. The constraint is what rejects"age".- The return type
T[K]is an indexed access type. It looks up the type of the property named byK.
The body obj[key] type-checks because key has type K, and K is known to be assignable to keyof T. The expression obj[key] therefore has type T[K], which matches the declared return type.
How inference works
The order of inference matters, and it explains why the result is precise.
The key detail is that K is inferred as the literal type "name", not as string. TypeScript keeps literal types when the type parameter's constraint includes literal types (here, keyof T is a union of string literals). If the constraint were plain K extends string, the result would still be a literal, but you would lose the link to T.
Why not just use keyof T directly?
You could write a version with one type parameter:
function getPropertyWeak<T>(obj: T, key: keyof T): T[keyof T] {
return obj[key];
}
const user = { id: 1, name: "Ada" };
const value = getPropertyWeak(user, "name"); // string | numberThis still rejects bad keys. But the return type is T[keyof T], the union of every property type, because nothing connects the particular key to the return type. The second type parameter K is what carries the specific key from the argument to the result. Use the K form whenever the return type depends on which key was passed.
Union keys give union results
If the key argument is itself a union, K becomes a union and T[K] distributes over it.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ada" };
const field = Math.random() > 0.5 ? "id" : "name";
const value = getProperty(user, field); // string | numberHere field has type "id" | "name", so K is that union and T[K] is number | string. This is accurate: at runtime the value is one of the two.
Optional properties
An optional property adds undefined to the looked-up type, and the generic function passes that through.
interface Profile {
id: number;
email?: string;
}
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const profile: Profile = { id: 7 };
const email = getProperty(profile, "email"); // string | undefined
if (email !== undefined) {
console.log(email.toUpperCase());
}The function does not hide the possibility that the property is missing. You must narrow the result before you use it as a string.
More functions built on the same constraint
The same two type parameters appear in many everyday helpers.
Writing a property
For a setter, the value must match the type of the chosen key. Putting T[K] in the parameter position does that.
function setProperty<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
obj[key] = value;
}
const point = { x: 1, y: 2, label: "origin" };
setProperty(point, "x", 10); // ok
setProperty(point, "label", "start"); // ok
// setProperty(point, "x", "ten"); // Error: string is not assignable to numberPlucking one key from many objects
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map((item) => item[key]);
}
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Grace" },
];
const names = pluck(users, "name"); // string[]
const ids = pluck(users, "id"); // number[]Picking several keys
When the parameter is an array of keys, K is inferred as the union of the literals in the array.
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 summary = pick(user, ["id", "name"]); // { id: number; name: string }The cast {} as Pick<T, K> is needed because an empty object literal is not yet a Pick<T, K>. It is the usual place where a small, local assertion is acceptable, since the loop fills in every key before the function returns.
Common errors and how to fix them
Passing a plain string variable
The constraint rejects a value typed as string, even if it happens to hold a valid key.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ada" };
const input: string = "name";
// getProperty(user, input); // Error: string is not assignable to "id" | "name"When the key comes from outside (a form field, a URL, parsed JSON), write a type guard that checks it at runtime.
function isKeyOf<T extends object>(obj: T, key: PropertyKey): key is keyof T {
return Object.prototype.hasOwnProperty.call(obj, key);
}
const user = { id: 1, name: "Ada" };
const input: string = "name";
if (isKeyOf(user, input)) {
const value = getProperty(user, input); // string | number
console.log(value);
}The guard narrows input from string to "id" | "name" inside the if. Without the runtime check, a cast such as input as keyof typeof user would silence the compiler but let a wrong key through.
Forgetting the constraint
Writing <T, K> with no extends keyof T gives this error on T[K]: "Type 'K' cannot be used to index type 'T'". The compiler needs the constraint to prove the lookup is valid.
Using the key as a string
keyof T can include string, number, and symbol keys. Code that treats the key as a string may fail to compile.
function describe<T, K extends keyof T & string>(obj: T, key: K): string {
return `${key} = ${String(obj[key])}`;
}
const user = { id: 1, name: "Ada" };
console.log(describe(user, "name")); // name = AdaWithout & string, the template literal ${key} fails because key might be a symbol. The intersection keyof T & string keeps only the string keys.
Index signatures widen the constraint
If T has a string index signature, keyof T is string | number, so any string passes the check and the result is the index signature's value type.
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const scores: { [player: string]: number } = { ada: 10 };
const score = getProperty(scores, "anything"); // number, but may be undefined at runtimeThe compiler cannot know which keys exist, so the safety check does no real work here. If you enable noUncheckedIndexedAccess, direct indexing such as scores["anything"] yields number | undefined, but T[K] in a generic return type does not pick up that extra undefined. Treat index-signature objects with care.
| Symptom | Likely cause | Fix |
|---|---|---|
| `Type 'K' cannot be used to index type 'T'` | Missing `extends keyof T` | Add the constraint |
| Return type is a wide union | Used `keyof T` as the parameter type instead of `K` | Use a separate type parameter `K` |
| `string` is not assignable to the key union | Key is a general `string` | Use a type guard like `isKeyOf` |
| Symbol conversion error in a template literal | `keyof T` includes `symbol` | Constrain with `keyof T & string` |
| Any key accepted | `T` has an index signature | Use a narrower type for `T` |
Choosing between this and simpler tools
Use K extends keyof T when the return or value type depends on the specific key. If you only need a fixed key, write the lookup directly, for example User["name"]. If you are transforming every key of a type rather than reading one, a mapped type such as { [K in keyof T]: ... } is the right tool, and the next chapter covers it.
Exercise
What is the inferred type of result below, and why does the compiler reject the commented line?
const config = { host: "localhost", port: 8080 };
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const result = getProperty(config, "port");
// getProperty(config, "timeout");
Show answer
result is number. T is inferred as { host: string; port: number }, K is inferred as the literal "port", and the return type T[K] resolves to number. The commented call is rejected because "timeout" is not assignable to keyof T, which is "host" | "port", so it fails the K extends keyof T constraint.
Exercise
Write a function getMany that takes an object and an array of keys, and returns an array of the matching property values. For getMany({ id: 1, name: "Ada" }, ["id", "name"]), what is the return type, and why is it not number[] or string[]?
Show answer
One correct version is:
function getMany<T, K extends keyof T>(obj: T, keys: K[]): T[K][] {
return keys.map((key) => obj[key]);
}
K is inferred as "id" | "name" from the array elements, so T[K] is number | string and the return type is (string | number)[]. It is not number[] or string[] because the array can hold either key, and the type system does not track which position holds which key.