Sub topic 4
Keys of a runtime object: keyof typeof
This chapter assumes you know what keyof does on an object type and what typeof does in a type position, both covered earlier in this tutorial. It also assumes you can read basic generics. Here you combine the two operators so that a plain JavaScript object becomes the single source of truth for a union of its keys.
The problem: keyof only accepts types
keyof is a type operator. Its operand must be a type, not a variable. If you hand it a variable name, the compiler complains that the name refers to a value.
const config = {
host: "localhost",
port: 8080,
};
// type Bad = keyof config;
// Error: 'config' refers to a value, but is being used as a type here.
// Did you mean 'typeof config'?typeof config, written in a type position, converts the value into its type. You can then apply keyof to that type. The combination reads left to right as "the keys of the type of config".
const config = {
host: "localhost",
port: 8080,
};
type Config = typeof config; // { host: string; port: number }
type ConfigKey = keyof Config; // "host" | "port"
// The same thing in one step:
type ConfigKeyShort = keyof typeof config; // "host" | "port"You do not need the intermediate alias. keyof typeof config is the idiomatic spelling.
Why this pattern is useful
The usual alternative is to write the key union by hand and then keep it in sync with the object. That duplicates information, and the two copies drift apart.
// Duplicated: adding a key to the object does not update the union.
type StatusManual = "active" | "paused" | "closed";
const statusLabels = {
active: "Active",
paused: "Paused",
closed: "Closed",
};With keyof typeof, the object is the only definition.
const statusLabels = {
active: "Active",
paused: "Paused",
closed: "Closed",
};
type Status = keyof typeof statusLabels; // "active" | "paused" | "closed"
function label(status: Status): string {
return statusLabels[status];
}
console.log(label("active")); // Active
// label("deleted"); // Error: Argument of type '"deleted"' is not assignable to parameter of type 'Status'.Add archived: "Archived" to statusLabels and Status gains "archived" with no other edit. Remove a key and every call site that uses it becomes a compile error. The lookup statusLabels[status] also type-checks without a cast, because every member of Status is a known key of the object.
Declared type versus inferred type
typeof reports the type the compiler inferred for the variable at its declaration. For object literals the inferred type is the widened one: host is string, not "localhost". This matters little for keyof, because the key names do not depend on the value types. Adding as const changes the values and makes properties readonly, but it leaves the keys the same.
const COLORS = {
red: "#ff0000",
green: "#00ff00",
} as const;
type ColorName = keyof typeof COLORS; // "red" | "green"
type ColorHex = (typeof COLORS)[ColorName]; // "#ff0000" | "#00ff00"Without as const, ColorHex would be plain string. The last line uses an indexed access type on the result of typeof, which is the next most common pairing. The parentheses are required: (typeof COLORS)[ColorName] means "the property types of the type of COLORS".
If you annotate the variable explicitly, typeof returns the annotation, not the literal's shape.
const labels: Record<string, string> = {
active: "Active",
};
type LabelKey = keyof typeof labels; // string | numberHere keyof sees a string index signature, so the specific key "active" is lost. If you want the exact key names, leave the object unannotated, or use as const or satisfies.
type Labelled = Record<string, string>;
const labels = {
active: "Active",
paused: "Paused",
} satisfies Labelled;
type LabelKey = keyof typeof labels; // "active" | "paused"satisfies checks that the object matches Labelled but keeps the inferred type, so the key names survive.
Using the key type with Object.keys
Object.keys returns string[], not an array of your key type. That means indexing inside a loop fails under strict.
const statusLabels = {
active: "Active",
paused: "Paused",
closed: "Closed",
};
type Status = keyof typeof statusLabels;
for (const key of Object.keys(statusLabels)) {
// console.log(statusLabels[key]);
// Error: Element implicitly has an 'any' type because expression of type 'string'
// can't be used to index type '{ active: string; paused: string; closed: string; }'.
}
for (const key of Object.keys(statusLabels) as Status[]) {
console.log(key, statusLabels[key]); // fine
}The assertion as Status[] is a promise you make to the compiler. TypeScript's object types are open, so a value typed as typeof statusLabels may carry extra properties at runtime. For an object literal you defined in the same file, the assertion is safe. For an object that arrives from elsewhere, check at runtime instead.
Narrowing a string to the key union
Data from outside your program, such as a URL parameter or a JSON field, arrives as string. A type guard turns it into Status.
const statusLabels = {
active: "Active",
paused: "Paused",
closed: "Closed",
};
type Status = keyof typeof statusLabels;
function isStatus(value: string): value is Status {
return Object.prototype.hasOwnProperty.call(statusLabels, value);
}
function describe(input: string): string {
return isStatus(input) ? statusLabels[input] : "Unknown";
}
console.log(describe("paused")); // Paused
console.log(describe("toString")); // UnknownThe guard uses hasOwnProperty on purpose. The expression value in statusLabels also returns true for inherited names such as "toString" and "constructor", so the guard would claim those strings are valid statuses. Because the guard derives from the object itself, the runtime check and the compile-time type cannot disagree.
Enums and classes behave differently
typeof applied to an enum or a class gives the type of the runtime object that the name creates, which is often not what you first expect.
For an enum, the name Direction is both a type (the union of its members) and a value (an object holding the members). keyof Direction is the keys of the member type. For a numeric enum that is the keys of number, such as toFixed. keyof typeof Direction is the list of member names.
enum Direction {
Up,
Down,
Left,
Right,
}
type DirectionName = keyof typeof Direction; // "Up" | "Down" | "Left" | "Right"
function move(name: DirectionName): Direction {
return Direction[name];
}
console.log(move("Left")); // 2Numeric enums also create a reverse mapping at runtime (Direction[2] is "Left"), but keyof typeof Direction includes only the names, not the numeric keys.
For a class, the class name as a type means the instance type, while typeof ClassName means the constructor function with its static members.
class Counter {
static created = 0;
value = 0;
increment(): void {
this.value += 1;
}
}
type InstanceKeys = keyof Counter; // "value" | "increment"
type StaticKeys = keyof typeof Counter; // "prototype" | "created"Use keyof Counter when you want instance members and keyof typeof Counter when you want statics. Note the extra "prototype" key on the constructor side.
Quick reference
| Expression | Operand | Result for `const config = { host: "localhost", port: 8080 }` | Column |
|---|---|---|---|
| `typeof config` | a value | `{ host: string; port: number }` | |
| `keyof config` | a value | Error: `config` is a value, not a type | |
| `keyof typeof config` | a value | `"host" \ | "port"` |
| `(typeof config)[keyof typeof config]` | a value | `string \ | number` |
Common mistakes
- Writing
keyof configon a variable. The fix iskeyof typeof config. - Using
typeofin value position and expecting a type. In an expression such asif (typeof x === "string"),typeofis the JavaScript operator and returns a string. It only produces a type when it appears where a type is expected, such as after:, aftertype X =, or inside<...>. - Annotating the object and losing the keys. An annotation like
Record<string, string>replaces the precise shape with an index signature, andkeyofthen returnsstring | number. - Expecting
as constto change the keys. It changes value types to literals and makes propertiesreadonly. The key union stays the same. - Calling
keyof typeofon a class or enum without checking which side you want. Instance keys, static keys, and enum member names are three separate things. - Trusting
inas a guard. It matches inherited properties. PreferObject.hasOwn(obj, value)where your target library supports it, orObject.prototype.hasOwnProperty.callotherwise.
Putting it together
The pattern most often seen in real code is a single object that drives a type, a lookup function, and a guard.
const handlers = {
start: (id: number) => `starting ${id}`,
stop: (id: number) => `stopping ${id}`,
} as const;
type Command = keyof typeof handlers; // "start" | "stop"
function run<C extends Command>(command: C, id: number): ReturnType<(typeof handlers)[C]> {
return handlers[command](id) as ReturnType<(typeof handlers)[C]>;
}
console.log(run("start", 7)); // starting 7The type Command comes from the object, the function parameter is constrained by it, and the return type is looked up through the same object. The assertion on the return is needed because TypeScript cannot prove that calling a union of functions yields the indexed return type for a generic C. Every type in this example is derived from handlers, so adding a command requires changing exactly one place.
Exercise
Given the code below, write the type Level so that it equals the union of the object's keys, and write the type Weight so that it equals the union of its value types as precise literals. Then say what Weight would be if as const were removed.
const LOG_LEVELS = { debug: 10, info: 20, error: 40 } as const;
Show answer
type Level = keyof typeof LOGLEVELS; // "debug" | "info" | "error"
type Weight = (typeof LOGLEVELS)[Level]; // 10 | 20 | 40
Without as const, the property types are widened to number, so Weight would be number. Level would be unchanged, because as const does not affect the keys.
Exercise
The function below is meant to accept any string and return a label or "Unknown", but it has a bug that lets "constructor" through as a valid key. Explain the bug and fix it. const labels = { a: "Alpha", b: "Beta" }; type LabelKey = keyof typeof labels; function isLabelKey(value: string): value is LabelKey { return value in labels; }
Show answer
The in operator also checks the prototype chain, and "constructor" is inherited from Object.prototype, so "constructor" in labels is true. The guard then claims the string is "a" | "b" when it is not. Fix it by testing own properties only:
function isLabelKey(value: string): value is LabelKey {
return Object.prototype.hasOwnProperty.call(labels, value);
}
Exercise
For class Cache { static size = 0; entries = new Map<string, number>(); clear(): void {} }, what are keyof Cache and keyof typeof Cache?
Show answer
keyof Cache is "entries" | "clear", the instance members. keyof typeof Cache is "prototype" | "size", the static side of the constructor.