Skip to main content

keyof

What keyof produces

keyof T gives you a union of the property names (keys) of a type T, as a literal union.

type Person = { name: string; age: number; isAdult?: boolean };

type PersonKey = keyof Person; // "name" | "age" | "isAdult"

Why it matters — safe property access

keyof lets you write functions that accept only real keys of an object. Pass a key that doesn't exist and it won't compile.

type Person = { name: string; age: number; isAdult?: boolean };

function getValue(key: keyof Person, person: Person) {
return person[key];
}

const val = getValue("name", { name: "Ajay", age: 23 }); // Valid: getValue("email", { name: "Ajay", age: 23 }); // Error: 'email' is not a key of Person

The real power: keyof + generics for typed lookups

Combined with a generic, keyof can make the return type follow the key you pass — the value type is exactly right, not a broad union.

function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}

const person = { name: "Ajay", age: 23 };
const name = getProp(person, "name"); // typed as string
const age = getProp(person, "age"); // typed as number

T[K] here is an indexed access type — the next topic.

keyof turns "the keys of this object" into a first-class type. It's the foundation for writing generic, type-safe utilities that operate on arbitrary object shapes.