TypeScript theorytheory 0/50 · 0%
Types · medium

27. keyof and lookup types

Deriving key unions and indexed access types.

`keyof T` produces a union of a type's property names as string literal types. Indexed access `T[K]` looks up the type of a specific property.

ts
interface Token { symbol: string; decimals: number; }

type TokenKey = keyof Token; // "symbol" | "decimals"

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

const t: Token = { symbol: "ETH", decimals: 18 };
const d = getProp(t, "decimals"); // number

This pattern gives fully type-safe generic property access — `getProp(t, "decimals")` returns `number`, and passing a key that doesn't exist on `Token` is a compile error, unlike an unchecked `obj[key]` with `key: string`.

Check your understanding

  1. 1. What does `keyof Token` produce for `interface Token { symbol: string; decimals: number; }`?

  2. 2. What does `T[K]` mean when `K extends keyof T`?

  3. 3. Why is `getProp(t, "decimals")` safer than plain `obj[key]` with `key: string`?