Q14 of 38 · TypeScript

What does the `keyof` operator do in TypeScript?

TypeScriptMidtypescriptkeyofgenericsindexed-accesstype-operators

Short answer

Short answer: `keyof T` produces a union type of all the string (and symbol) keys of type `T`. Combining `keyof` with `T[K]` (indexed access) lets you write generic functions that safely access an object's property by a validated key, preventing typos and accessing non-existent properties at compile time.

Detail

keyof T is a type operator that yields a union of all property keys of type T. For a type with string keys, keyof T is a string literal union.

Basic use: keyof User where User = { id: number; name: string } produces "id" | "name".

With indexed access (T[K]): Combining keyof with an indexed type parameter K extends keyof T and T[K] gives you the type of the value at that key — the backbone of safe property access in generic functions.

typeof: Applied to a runtime value, typeof obj produces the TypeScript type of obj. Combined with keyof, keyof typeof CONFIG gives the union of all keys of a const object.

In test helpers: keyof is used to write type-safe data accessors, sort functions, and fixture factories that accept property names as arguments without losing type information.

// EXAMPLE

interface User {
  id: number;
  name: string;
  email: string;
}

// keyof — union of keys
type UserKey = keyof User; // "id" | "name" | "email"

// Safe property accessor
function getField<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
const user: User = { id: 1, name: "Alice", email: "a@b.com" };
const name = getField(user, "name");  // inferred: string
const id   = getField(user, "id");    // inferred: number
// getField(user, "typo");            // Error: not a key of User

// keyof typeof for const objects
const CONFIG = { timeout: 5000, retries: 3, env: "test" } as const;
type ConfigKey = keyof typeof CONFIG; // "timeout" | "retries" | "env"

// Sort generic — type-safe
function sortBy<T>(items: T[], key: keyof T): T[] {
  return [...items].sort((a, b) => (a[key] > b[key] ? 1 : -1));
}

// WHAT INTERVIEWERS LOOK FOR

Understanding `keyof T` as a union of key names. The `K extends keyof T` + `T[K]` pattern for safe generic property access. `keyof typeof` for const objects. Applied to test helpers is a strong practical signal.

// COMMON PITFALL

Using `string` as the type for a property key instead of `keyof T` — this loses type safety; the compiler can't verify the property exists or infer the value type.