The Analogy: The Key Cabinet Behind the Front Desk
Behind every hotel front desk hangs the key cabinet: a shallow wooden case of labelled hooks, one hook per room, plus a few special hooks off to the side -- the master, the safe, the garage fob. The set of room numbers the hotel can hand out is not written on a separate list kept in a drawer; it is simply whatever labels are on the hooks. Add a room and you add a hook; renumber one and you re-label its hook. The cabinet is the single source of truth, and the list of valid keys is read off the board, never maintained beside it. That reading-off is exactly what keyof and typeof do: you keep your data in one place and derive the names and types from it, instead of typing a second list by hand that quietly falls out of step.
The two operators split the work. typeof, used where a type is expected, asks "what is the shape of this thing as it actually stands?" -- it reads the cabinet and reports which hooks exist and what kind of thing hangs on each. keyof asks the narrower question "what are the labels?" -- it prints the set of hook names and nothing else. And indexed access, T[K], reads one named hook: hand it the label "safe" and it tells you the kind of key on that hook, which need not be the same kind as hangs on hook "204". A room key, a flat safe key, a plastic fob: different hooks, different kinds, all named off the one board.
There is a catch in how carefully you record the board, and it is the whole reason as const exists. Note the cabinet loosely -- "a row of hooks, each holding some key" -- and the labels collapse to just "labels", the type of a hook-name becomes merely string, and the derived list is worthless because it admits any string at all. Record each hook with its exact stamped designation and the label set becomes the precise union of the names that are really there. Pinned that way, one array or object literal is at once the runtime board the staff take keys from and the exact type the compiler checks against, and adding a hook updates both in the same stroke.
The failure mode is the laminated card. Somewhere at the desk a well-meaning clerk keeps a separate typed-up list of room numbers, and the day a room is added to the cabinet but not to the card, the two disagree: a guest asks for a key the card swears exists and there is no hook for it, or the card still lists a room under a number that was changed last spring. A hand-kept list beside the source is a second truth waiting to rot. Derive the list from the board with keyof typeof, and there is only ever one truth: the list cannot name a hook the cabinet lacks, because the list is the cabinet's labels.
Syntax or Core Structure
keyof T is a type: the union of T's property names. typeof v, in a type position, is the type the compiler inferred for the value v. Put them together as keyof typeof v and you turn a plain object into the union of its key names.
// src/desk.ts
interface Room {
number: string;
floor: number;
occupied: boolean;
}
type RoomKey = keyof Room; // "number" | "floor" | "occupied"
type RoomValue = Room[RoomKey]; // string | number | boolean
const desk = {
open: true,
staff: 3,
branch: "harbour"
};
type Desk = typeof desk; // { open: boolean; staff: number; branch: string }
type DeskKey = keyof typeof desk; // "open" | "staff" | "branch"
// keyof is a type; to hold the names at run time, list them typed as the key union
const roomKeys: RoomKey[] = ["number", "floor", "occupied"];
// const wrong: RoomKey[] = ["number", "level"]; // refused: "level" is not a key of Room
console.log(roomKeys.join(" "));
console.log(desk.staff, desk.branch);
Output:
number floor occupied
3 harbour
RoomKey is the union of Room's three property names, and RoomValue is the union of the types stored at those names. Desk is read straight off the desk value with typeof, and DeskKey lists its keys. The roomKeys array is hand-listed but typed RoomKey[], so the compiler checks each entry against the key union, and the commented wrong line is refused because "level" is not a key. Note that keyof produces a type, not a runtime array: to iterate the names at run time you either write them out, typed as the key union, or derive them from an as const value, which the next section does.
Technical Depth: Two typeofs, Reading One Hook, and the as const Multiplier
The same keyword typeof means two different things depending on which world it stands in, indexed access reads the type off a single key, and as const is the switch that decides whether any of it is precise or worthless.
The runtime typeof and the type-level typeof
typeof on the left of === is JavaScript: it computes a string at run time. typeof after a colon or inside type X = ... is TypeScript: it reads the type the compiler inferred. Same word, two worlds, and telling them apart clears up most of the confusion.
// src/twotypeof.ts
const branch = "harbour";
// runtime typeof: a real string, produced when the program runs
const kind = typeof branch; // the value "string"
// type-level typeof: the type the compiler inferred, usable only as a type
type Branch = typeof branch; // the literal type "harbour"
const only: Branch = "harbour"; // nothing else is assignable
// const other: Branch = "pier"; // refused: not "harbour"
console.log(kind);
console.log(only);
Output:
string
harbour
The first typeof runs as JavaScript and yields the string "string", which is what prints. The second typeof never runs at all: it is a type, "harbour", and it constrains only so tightly that the commented other is refused. On the left of === you are asking the running program; after a colon you are asking the compiler what it worked out.
Indexed access reads one hook
T[K] reads the type stored at a key, exactly as pulling one hook off the cabinet reads the kind of key there. T[number] is the same move on an array type: it reads the element type, and over an as const array that is the union of the literal elements.
// src/indexed.ts
interface Tariff {
rate: number;
room: string;
}
type Rate = Tariff["rate"]; // number, read off the 'rate' hook
const RATES = [20, 35, 50] as const;
type RateLiteral = typeof RATES[number]; // 20 | 35 | 50
const total: number = RATES.reduce((sum, r) => sum + r, 0);
const one: Rate = 35;
console.log(total, one);
Output:
105 35
Rate is Tariff["rate"], the type on the rate hook, which is number. RateLiteral uses typeof RATES[number] to read the element type off the as const array, giving the union 20 | 35 | 50 rather than a bare number. At run time the array is just three numbers, so reduce totals them to 105, and one is a plain Rate. The array is one thing serving two purposes: the runtime list you sum, and the type union you check against.
as const is the multiplier
Without as const an array literal widens to string[] and the derived type is useless; with it, the literal keeps its exact members and keyof typeof turns an object into the precise union of its keys. This is the pattern that replaces enum in modern code: no emitted runtime construct, a plain object at run time, and it tree-shakes.
// src/roles.ts
const ROOMS = ["single", "double", "suite"] as const;
type RoomType = typeof ROOMS[number]; // "single" | "double" | "suite"
const STATUS = { Free: "free", Booked: "booked" } as const;
type StatusKey = keyof typeof STATUS; // "Free" | "Booked"
type StatusValue = typeof STATUS[StatusKey]; // "free" | "booked"
const pick: RoomType = "double";
const state: StatusValue = STATUS.Booked;
// const bad: RoomType = "triple"; // refused: not one of the three
console.log(ROOMS.length, pick);
console.log(state);
Output:
3 double
booked
Output (tsc, for the commented line):
error TS2322: Type '"triple"' is not assignable to type '"single" | "double" | "suite"'.
ROOMS is frozen with as const, so typeof ROOMS[number] is the literal union and "triple" is refused. STATUS gives two derived types at once: keyof typeof STATUS is the key union "Free" | "Booked", and indexing by that key gives the value union "free" | "booked". Add a room to the array or a status to the object, and every one of these types updates with no second edit -- the single source of truth the cabinet insists on.
The operators at a glance
Each reads something and gives back a type; the last three are the ones you reach for weekly.
| Expression | Reads | Gives you |
|---|---|---|
keyof T | a type | the union of its property names |
typeof v (type position) | a value | the value's inferred type |
keyof typeof v | a value | the union of that value's key names |
T[K] | a type and a key | the type stored at that key |
T[number] | an array type | the element type |
typeof arr[number] | an as-const array | the union of its element literals |
ReturnType<typeof fn> | a function value | the type it returns |
The bottom row earns its place: ReturnType<typeof createStore> is how you type the result of a factory or a third-party helper without copying its shape by hand, so the type follows the function if the function changes.
Real World Example: A Front-Desk Settings Registry
Every property runs on a bundle of small settings: the hour check-in opens, the hour checkout closes, how many guests a standard room sleeps, which currency the till prints, whether the floor is smoking. The front desk needs one place those defaults live, a way for a duty manager to override a few for the night, and a report that shows at a glance what was moved off standard. The way to keep it honest is to hold the defaults as a single pinned literal and read everything else off it -- the set of valid setting names, the kind of value each setting carries -- so that adding a setting is a one-line change in exactly one place.
// src/registry.ts
const DEFAULTS = {
checkinHour: 15,
checkoutHour: 11,
maxGuests: 4,
currency: "GBP",
smoking: false
} as const;
type SettingKey = keyof typeof DEFAULTS; // the five names, read off DEFAULTS
interface Settings {
checkinHour: number;
checkoutHour: number;
maxGuests: number;
currency: string;
smoking: boolean;
}
const FIELD_ORDER: readonly SettingKey[] = [
"checkinHour", "checkoutHour", "maxGuests", "currency", "smoking"
];
function base(): Settings {
return { ...DEFAULTS };
}
// value is typed Settings[K], so each key demands its own kind of value
function set<K extends SettingKey>(s: Settings, key: K, value: Settings[K]): Settings {
const next: Settings = { ...s };
next[key] = value;
return next;
}
function report(cur: Settings): string {
const w0 = 14, w1 = 8;
const pad = (t: string, n: number) => t + " ".repeat(Math.max(0, n - t.length));
const changed = FIELD_ORDER.filter((k) => String(cur[k]) !== String(DEFAULTS[k]));
const lines: string[] = [];
lines.push("settings: " + FIELD_ORDER.length + ", changed: " + changed.length);
lines.push(pad("FIELD", w0) + pad("DEFAULT", w1) + "CURRENT");
for (const k of FIELD_ORDER) {
lines.push(pad(k, w0) + pad(String(DEFAULTS[k]), w1) + String(cur[k]));
}
lines.push("changed: " + changed.join(", "));
let total = 0;
for (const k of FIELD_ORDER) {
const v = cur[k];
if (typeof v === "number") total += v;
}
lines.push("numeric total: " + total);
return lines.join("\n");
}
const s0 = base();
const s1 = set(s0, "checkinHour", 14);
const s2 = set(s1, "maxGuests", 6);
const s3 = set(s2, "currency", "EUR");
const current = s3;
// set(s0, "wifi", 14); // refused: "wifi" is not a SettingKey
// set(s0, "checkinHour", "late"); // refused: number expected, string given
console.log(report(current));
Output:
settings: 5, changed: 3
FIELD DEFAULT CURRENT
checkinHour 15 14
checkoutHour 11 11
maxGuests 4 6
currency GBP EUR
smoking false false
changed: checkinHour, maxGuests, currency
numeric total: 31
The registry keeps DEFAULTS as an as const object, and SettingKey is keyof typeof DEFAULTS -- the union of the five names, read straight off the board rather than typed a second time. The set function is generic over K extends SettingKey, and its value parameter is typed Settings[K] by indexed access, so the compiler demands a number when you set maxGuests and a string when you set currency; the two commented calls are refused, one for an unknown key and one for a value of the wrong kind. Because set returns a fresh object rather than mutating in place, s0 through s3 are a chain of immutable snapshots, and current is simply the last of them.
The report walks FIELD_ORDER -- itself typed SettingKey[], so it cannot list a name the cabinet lacks -- and for each key reads the default off DEFAULTS[k] and the live value off cur[k], both by indexed access. It counts a field as changed when its string form differs from the default's, sums the settings whose current value is a number, and prints that total. Add a sixth setting to DEFAULTS and SettingKey grows by one on its own; the compiler then flags FIELD_ORDER as missing an entry, which is the reminder arriving exactly where the work is, not in a comment nobody reads.
The code has real limits worth naming. The sharpest is a design flaw hiding in plain sight: Settings is a hand-written interface kept beside DEFAULTS rather than derived from it, and it is written that way on purpose so its value types are widened -- a plain number, not the literal 15 -- so a setting can be changed at all. That widening is correct: a mapped type over typeof DEFAULTS would freeze checkinHour to the literal 15 and make set(s0, "checkinHour", 14) fail to compile. But the price is a second source of truth, because keyof typeof DEFAULTS updates itself when you add a field while Settings does not, so the two can silently drift until a Settings[K] lookup surfaces the gap. Beyond that, set does a shallow spread, so a setting whose value was itself an object would be shared and not copied; and change detection compares String(...) forms, which would call the number 4 and the string "4" equal -- harmless here because every value is a primitive of a fixed kind, but not a habit to carry to nested data.
Common Mistakes
- Forgetting
as conston a lookup object. Without it,{ Free: "free" }widens to{ Free: string }, sotypeof obj[keyof typeof obj]collapses tostringand every union you derive is worthless. Pin the literal first, then derive from it. - Expecting
keyofto hand you a runtime array.keyof Tis a type and emits nothing. To loop over the names when the program runs you need a real array, either written out and typed as the key union or read from anas constvalue withObject.keys. - Confusing the runtime
typeofwith the type-level one.typeof xbefore a colon or insidetype X =reads the compiler's inferred type;typeof xin an expression computes a string when the program runs. They share a spelling and nothing else. - Indexing a type with a key it may not have.
T[K]only type-checks whenKis known to be a key ofT; passing a barestringgives an implicit-any or index error under strict settings. Constrain the key withK extends keyof T. - Keeping a second, hand-typed list of the keys. The moment the names live in two places, one falls behind the other. Derive the list from the data with
keyof typeofso there is a single source of truth that cannot rot. - Reading a literal off an array that is not
as const.typeof arr[number]gives a precise union only whenarris frozen withas const; on a normal array it is just the element type, so you lose the exact precision you reached for. - Deriving a type from a
letbinding.typeof von a mutable binding uses the widened type, not the literal you assigned, because the binding could change later. Useconst, andas constwhen the literal must be preserved. - Assuming
keyofincludes only the keys you wrote. On built-in types and anything with an index signature,keyofcan include more than your own properties -- numeric indices, inherited members -- so a union you expected to be small comes out wider. - Reaching for
enumout of habit. Aconstobject plustypeof obj[keyof typeof obj]gives the same closed set of values with no emitted runtime construct and clean tree-shaking, and it avoids the surprising assignability rules that numericenums bring.
Best Practices
- Pin every lookup table with
as const. It is the switch that turns loosestringandnumbertypes into the exact literal unions the rest of your derivations depend on. - Derive key types, never retype them. Write
keyof typeof CONFIGinstead of spelling the names out again; a derived union cannot drift from the object it is read from. - Constrain generic key parameters with
extends keyof. A function that takes a key should declareK extends keyof T, so callers get autocompletion and a compile error for a bad key rather than a run-timeundefined. - Type the value by indexed access. When a function reads or writes one field, type its value parameter
T[K]; the compiler then enforces the right kind of value per key with no overloads. - Prefer
as constobjects toenum. Same closed set, no runtime cost, and the value union comes for free fromtypeof obj[keyof typeof obj]. - Keep the source of truth a single literal. One pinned array or object should feed both the runtime list and every derived type, so adding a member is a one-line change with no second edit.
- Type runtime key arrays as the key union. When you must list keys at run time, annotate the array as the key-union array so a typo or a stale entry is caught at compile time, not in production.
- Name derived types for their meaning.
SettingKey,RoomType, andStatusValueread far better at call sites than an inlinedkeyof typeof ...expression, and they document what the union stands for.
Practice Exercises
- A menu-price reader. Pin a
PRICESobject of dish names to pence withas const, deriveDish = keyof typeof PRICES, and writepriceOf(dish: Dish)that returns the price by indexed access. Confirm that an unknown dish name is a compile error, not a run-timeundefined. - A typed event map. Given an
as constobject mapping event names to payload shapes, derive the event-name union withkeyof typeofand writeonso that the handler's argument type is read off the map by indexed access for whichever event name is passed. - A config diff. Extend the registry so
reportalso returns the list of unchanged fields, and prove with a second run that the changed list and the unchanged list together coverFIELD_ORDERexactly once, with no name in both. - Replace an enum. Take an existing
enum Direction, rewrite it as anas constobject, derive the value union withtypeof obj[keyof typeof obj], and check that every place that used the enum still compiles without further change.