Type-safe property access
A generic function accepts an object and a property name while rejecting keys that are not present.
TypeScript · Const
keyof T creates a type containing the permitted keys of T. Explicit properties produce literal-key unions, while index signatures can produce string, number, or both.
In a type position, keyof T produces a union representing the keys permitted by T. For ordinary object properties these are literal types; index signatures can widen the result to string or number, and JavaScript’s string coercion can make a string index signature include number as well.
keyof T| Name | Type | Description |
|---|---|---|
T | type | The object type whose permitted property names are queried. |
A union of the permitted property-name types for the input type; depending on the type, members can be string, number, symbol, or literal key types.
keyof creates a union of the corresponding key literals.type Point = { x: number; y: number }, keyof Point is equivalent to "x" | "y".keyof result to derive a new type from every property.string | number.type Point = { x: number; y: number };
type PointKey = keyof Point;
function read<T, K extends keyof T>(object: T, key: K): T[K] {
return object[key];
}
const point: Point = { x: 10, y: 20 };
const x = read(point, "x"); // number
This generic helper accepts only keys belonging to the object and returns the corresponding property type.
A generic function accepts an object and a property name while rejecting keys that are not present.
A derived type needs one transformed member for each property in another type.
An API must expose a finite set of valid property-name options based on a model.
keyof produce for a normal object type?keyof T is a type-level query that produces the permitted property names of T. For { x: number; y: number }, it is equivalent to "x" | "y".
Follow-up: How would you restrict a generic key to strings? Use Extract<keyof T, string> when the implementation cannot handle numeric or symbol keys.
keyof used in a type-safe property accessor?A generic parameter can be constrained with K extends keyof T, guaranteeing that key is valid for obj. Indexed access T[K] then represents the value type associated with that key.
Follow-up: How can the same relationship type a setter? Declare value: T[K], so the value must match the selected property’s type.
keyof?For a numeric index signature, keyof produces number. For a string index signature, it produces string | number, reflecting that numeric property access is coerced to a string in JavaScript.
Follow-up: What happens with symbol-named properties? Modern TypeScript includes symbol-like property names in keyof results, so the result is not limited to strings and numbers.
Indexed Access TypesMapped TypesType OperatorsExtractGenerics