0Pricing
TypeScript Academy · Lesson

Combining typeof and keyof

Derive precise types by chaining type operators.

Combining typeof and keyof is a free TypeScript Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Power Combo

Individually, typeof derives a type from a value and keyof lists a type's keys. Together — keyof typeof value — they produce a union of a value's actual keys, enabling fully type-safe access.

keyof typeof in Action

Start with a const object, capture its type with typeof, then list its keys with keyof. The result is a union of the object's literal key names.

const colors = { red: "#f00", green: "#0f0" }
type ColorKey = keyof typeof colors // "red" | "green"
const k: ColorKey = "red"
console.log(colors[k])

Why This Pattern Exists

You often have a runtime object but no separate interface. keyof typeof gives you a key type without duplicating the object's shape as a hand-written type.

const status = { active: 1, inactive: 0, pending: 2 }
type Status = keyof typeof status // "active" | "inactive" | "pending"
const s: Status = "pending"
console.log(status[s]) // 2

Type-Safe Access by Key

A function parameter typed as keyof typeof obj rejects invalid keys at compile time, so indexed access inside is guaranteed safe.

const rates = { usd: 1, eur: 1.1, gbp: 1.3 }
function rate(currency: keyof typeof rates): number {
  return rates[currency]
}
console.log(rate("eur")) // 1.1
// rate("jpy") // Error: not a key

Enum-Like Constant Objects

A common idiom: define an as const object as a pseudo-enum, then derive both its key and value types from it.

const Direction = { Up: "UP", Down: "DOWN" } as const
type DirKey = keyof typeof Direction // "Up" | "Down"
type DirValue = typeof Direction[keyof typeof Direction] // "UP" | "DOWN"
console.log(Direction.Up)

Keys vs Values

Note the distinction: keyof typeof obj gives the key names, while typeof obj[keyof typeof obj] gives the value types. Pick whichever your API needs.

const sizes = { sm: 8, md: 16, lg: 24 } as const
type SizeName = keyof typeof sizes // "sm" | "md" | "lg"
type SizeValue = typeof sizes[keyof typeof sizes] // 8 | 16 | 24
const v: SizeValue = 16
console.log(v)

Generic getProperty

The classic type-safe getter constrains a key parameter with K extends keyof T and returns T[K], so the result type matches the looked-up property exactly.

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key]
}
const user = { id: 1, name: "Ada" }
const name = getProperty(user, "name") // string
console.log(name)

Return Type Follows the Key

Because the return is T[K], each call's result type adapts to the specific key passed — a number for one key, a string for another.

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key]
}
const u = { id: 1, name: "Ada" }
const id = getProperty(u, "id")     // number
const nm = getProperty(u, "name")   // string
console.log(id, nm)

Invalid Keys Are Rejected

Passing a key that does not exist on the object is a compile error. The generic constraint enforces it before the code ever runs.

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key]
}
const u = { id: 1 }
// getProperty(u, "missing") // Error: not a key of u
console.log(getProperty(u, "id"))

A Type-Safe Setter

The same machinery builds a setter: the value parameter is T[K], so you can only assign a value of the correct type for that key.

function setProperty<T, K extends keyof T>(obj: T, key: K, value: T[K]): void {
  obj[key] = value
}
const u = { id: 1, name: "Ada" }
setProperty(u, "name", "Leo")
console.log(u.name)

Putting It Together

The keyof typeof pattern plus generic T[K] access gives you safe, reusable utilities over real objects — the backbone of typed config readers, lookups, and form helpers.

const theme = { primary: "#007", danger: "#f00" } as const
function color(name: keyof typeof theme): string {
  return theme[name]
}
console.log(color("danger")) // #f00

Quick Check

Test your understanding of combining typeof and keyof.

Recap

keyof typeof value derives a union of a value's actual keys without writing a separate interface, making indexed access type-safe. Distinguish key types (keyof typeof obj) from value types (typeof obj[keyof typeof obj]). The generic pattern getProperty<T, K extends keyof T>(obj, key): T[K] returns the exact looked-up type and rejects invalid keys at compile time.

Frequently asked questions

Is the “Combining typeof and keyof” lesson free?

Yes — the full text of “Combining typeof and keyof” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Combining typeof and keyof”?

Derive precise types by chaining type operators. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Combining typeof and keyof” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The typeof Type Operator
  2. The keyof Type Operator
  3. Indexed Access Types
  4. Combining typeof and keyof
← Back to TypeScript Academy