Skip to content

Keyof Operator

In one line

The keyof operator takes an object type and returns a union of its property names (keys), enabling type-safe property access.

In simple words

The keyof operator extracts the keys of an object type as a union of string literal types. For type T = { a: string; b: number }, keyof T is "a" | "b".

This is useful for creating type-safe property accessors, generic functions that work with any property, and mapped types. Combined with indexed access types (T[K]), it enables powerful type-level programming.

For example, function get<T, K extends keyof T>(obj: T, key: K): T[K] lets you access any property of any object with full type safety — the return type matches the property's type.

Example

typescript
interface Person { name: string; age: number; }
type PersonKey = keyof Person; // "name" | "age"

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

const p: Person = { name: "Alice", age: 30 };
const n = get(p, "name"); // type: string

keyof extracts keys as a union. The get function uses keyof for type-safe property access.

Related terms

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary