Sub topic 8
Type-Safe Property Access with `K extends keyof T`
This chapter assumes you know interfaces, type aliases, union types, and basic generics. You should also be comfortable reading JavaScript objects and functions.
A generic property-access function should accept only keys that exist on an object. It should also return the correct type for the selected property. TypeScript expresses that relationship with K extends keyof T.
Constraining a key to an object
Suppose an object has two properties:
const user = {
id: 1,
name: "Ada",
};A function that accepts any string is unsafe:
function getValue(obj: object, key: string) {
return obj[key as keyof typeof obj];
}The caller can pass "age" even though user has no age property. The type system cannot connect the particular object to the particular key.
A generic function keeps those types connected:
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"); // string
const id = getProperty(user, "id"); // number
// Error: "age" is not assignable to "id" | "name"
// const age = getProperty(user, "age");Here, T represents the object type. For user, TypeScript infers:
type User = {
id: number;
name: string;
};The expression keyof T produces the union of valid property names:
type UserKey = keyof User; // "id" | "name"K extends keyof T means that K must be one of those property names. The return type T[K] then looks up the value type for that key.
How inference connects the arguments
When you call getProperty(user, "name"), TypeScript infers:
Tas{ id: number; name: string }Kas"name"T[K]asstring
When you call getProperty(user, "id"), K becomes "id" and T[K] becomes number.
This is more precise than returning a union such as string | number. A union would say that every call might return either type. The indexed access type T[K] preserves the relationship between the selected key and the selected value.
flowchart TD
A["Object type T"] --> B["keyof T"]
B --> C["Allowed key type K"]
C --> D["Indexed access T[K]"]
D --> E["Exact property value type"]Writing related generic functions
The same constraint works when setting a property:
function setProperty<T, K extends keyof T>(
obj: T,
key: K,
value: T[K],
): void {
obj[key] = value;
}
const settings = {
retries: 3,
debug: false,
};
setProperty(settings, "retries", 5);
setProperty(settings, "debug", true);
// Error: the value must be boolean for the "debug" key
// setProperty(settings, "debug", "yes");The key and value remain linked. "debug" selects boolean, so the third argument must be a boolean. "retries" selects number.
You can also use a key parameter without making the function generic over the object:
function hasKey<T extends object>(
obj: T,
key: PropertyKey,
): key is keyof T {
return key in obj;
}However, a type predicate involving arbitrary keys often needs additional narrowing before indexing. For ordinary property access, K extends keyof T is usually the clearer design.
Common errors
Using `string` instead of `keyof T`
This loses the connection between the object and the key:
function unsafeGet<T>(obj: T, key: string) {
// obj[key]; // Error: string cannot safely index T
return undefined;
}Use K extends keyof T when the key must come from the object type.
Expecting `keyof` to return only strings
For a normal object with named properties, keyof usually produces string literal types. Index signatures behave differently. For example, keyof { [key: string]: boolean } is string | number, because JavaScript converts numeric property access to string keys.
Forgetting optional properties
If a property is optional, its indexed type includes undefined when strict null checking is enabled:
interface Profile {
name: string;
nickname?: string;
}
function readProfile<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const profile: Profile = { name: "Ada" };
const nickname = readProfile(profile, "nickname");
// string | undefinedThe caller must handle the missing value before using it as a definite string.
Exercise
What is the return type of getProperty({ active: true, count: 2 }, "active"), and why?
Show answer
The return type is boolean. TypeScript infers K as "active", then evaluates T[K] as the type of the active property.