Lessons · TypeScript · keyof: the names of the keys
The keys as a type
keyof T is the union of T's property names as string literals: keyof { x: number; y: number } is 'x' | 'y'.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
A getter that takes a property name should only accept real property names. keyof makes the compiler check the name and know the result's type.
How to think about it
Pair keyof with a generic: <T, K extends keyof T>(obj: T, key: K) returns T[K], the exact type of that property.
Worked example
type Point = { x: number; y: number };Two keys.type Key = keyof Point;'x' | 'y'.
function getKey(p: Point, k: Key): number { return p[k]; }Only real keys are accepted.getKey({ x: 1, y: 2 }, "x");Fine.getKey({ x: 1, y: 2 }, "z");Error: 'z' is not a key of Point.Your turn
A typed property picker.
function pickKey<T, K extends T>(obj: T, key: K) { return obj[key]; }Solve one with the compiler running
The trap
keyof a type with an index signature is string | number, not your field names. It lists only the keys the type declares.
Practise keyof: the names of the keys on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.