The keyof and typeof type operators
Deriving types from what already exists: keyof for a type's keys, type-level typeof for a value's type, and keyof typeof to get keys from a runtime object.
Union and literal typesObject types, optional and readonly propertiestypeof, instanceof, and in narrowing
The keyof and typeof type operators
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Type-level programming starts with deriving types from things that already exist, so a second hand-written copy can't drift out of sync with the original.
- `keyof T` produces a union of the property names of `T`, so `keyof { a: number; b: string }` is `"a" | "b"`.
- On a type with a string index signature, `keyof` gives `string | number`, because JavaScript turns numeric property keys into strings and `obj[0]` reads the same slot as `obj["0"]`.
- `typeof` in an expression is the runtime JavaScript operator that returns a string like `"object"`; `typeof` in a type position asks the compiler for the static type of a variable or property.
- Type-level `typeof` only accepts a name or a property path such as `typeof config.server`, not a function call or other arbitrary expression.
- `keyof typeof obj` reads right to left: take the type of the runtime object, then take its keys, which turns an object literal into the single source of truth for a key union.
Two lists that have to agree
Say your app has a settings object and a function that reads one setting by name:
interface Settings {
theme: "light" | "dark";
fontSize: number;
autosave: boolean;
}
function readSettingLoose(settings: Settings, key: string) {
return settings[key as keyof Settings];
}
Typing key as string lets callers pass "colour" and find out at runtime. You could write the union "theme" | "fontSize" | "autosave" by hand, but now the property names live in two places. Someone adds language to Settings next month, forgets the union, and nothing complains.
This group of lessons is about avoiding that second copy. Instead of restating facts about your types, you compute new types from the ones you already have. keyof and typeof are the two most basic tools for that.
keyof: the keys of a type
keyof takes an object type and produces a union of its property names as string literal types:
type SettingKey = keyof Settings; // "theme" | "fontSize" | "autosave"
function readSetting(settings: Settings, key: SettingKey) {
return settings[key];
}
declare const current: Settings;
readSetting(current, "theme"); // fine
readSetting(current, "colour"); // Error: not assignable to type 'keyof Settings'
SettingKey is no longer a copy. Add language to the interface and it joins the union automatically, along with autocomplete in every call to readSetting.
One limit is worth noticing: readSetting returns "light" | "dark" | number | boolean, the union of every property type, whichever key you pass. Linking the return type to the specific key needs a generic and an indexed access type, which is the next lesson.
keyof on index signatures
For an object with an index signature, there are no fixed names to list, so keyof returns the key type itself. There’s a surprise in the string case:
type Scores = { [player: string]: number };
type ScoreKey = keyof Scores; // string | number
type Lines = { [line: number]: string };
type LineKey = keyof Lines; // number
const someKey: ScoreKey = 42; // fine
The number in string | number comes from JavaScript itself. Property keys are always strings (or symbols) at runtime, and a number used as a key is converted, so scores[0] and scores["0"] read the same property. A string index signature therefore accepts numeric keys too, and keyof says so.
The same idea explains a common snag. keyof T on an arbitrary type can include string, number and symbol keys. When you need only the string ones, for example to build a string from a key, write string & keyof T or Extract<keyof T, string>.
typeof: two operators with one name
JavaScript already has a typeof operator. TypeScript adds a second one that only works in type positions, and the position decides which you get:
const defaults = {
theme: "light",
fontSize: 14,
autosave: true,
};
const kind = typeof defaults; // runtime JavaScript: the string "object"
type Defaults = typeof defaults;
// { theme: string; fontSize: number; autosave: boolean }
type FontSize = typeof defaults.fontSize; // number
The first typeof survives into the compiled JavaScript and produces one of a handful of strings at runtime. It’s the one you used for narrowing. The second is a compile-time query. It asks the checker “what type did you infer for this variable?” and is erased with all other types.
Think of it as reading a label off a box that’s already on the shelf. You don’t describe the box again; you point at it. That’s why type-level typeof only accepts a name or a property path such as typeof defaults.fontSize. It can’t run code, so typeof readSetting(current, "theme") is a syntax error. To get what a function returns, use ReturnType<typeof readSetting>, covered in utility types for unions and functions.
Notice also that theme came out as string, not "light". Inference widens literals in mutable objects. Add as const to the object if you want the literal types and readonly properties instead.
keyof typeof: keys from a runtime object
The two operators combine into a pattern you’ll see constantly. Often the real source of truth isn’t an interface but an object in your code, like a table of command handlers:
const handlers = {
save: () => console.log("saving"),
open: (path: string) => console.log("opening", path),
close: () => console.log("closing"),
};
type BrokenCommand = keyof handlers; // Error: 'handlers' refers to a value
type Command = keyof typeof handlers; // "save" | "open" | "close"
function hasHandler(name: string): name is Command {
return name in handlers;
}
keyof needs a type, and handlers is a value, hence the error. Read keyof typeof handlers from right to left: typeof turns the value into its type, then keyof lists that type’s keys. Adding a print handler to the object updates Command with no other edits.
About the video
Dillion Megida’s short video on Deeecode covers exactly this core move: keyof on a type, typeof to bring a value into the type world, and keyof typeof to derive a key union from a runtime object. At under four minutes it’s a quick reinforcement of the sections above. It doesn’t cover index signatures or the runtime versus compile-time split in detail, which is why the written lesson spends time on both. For keyof used inside generic constraints, the Jack Herrington link below is a good next step.
Check yourself
Why is `keyof Settings` better than writing the union `"theme" | "fontSize"` by hand?
The hand-written union is a second copy of information that already lives in `Settings`. Add or rename a property and the copy goes stale without any error. `keyof Settings` is recomputed from the interface every time, so the key union always matches the real properties.
What is `keyof { [key: string]: boolean }`, and why?
It is `string | number`. A string index signature accepts numeric keys too, because JavaScript converts a number used as a property key into a string, so `obj[1]` and `obj["1"]` hit the same property. TypeScript reflects that by including `number` in the key type.
In `const kind = typeof value;` and `type Kind = typeof value;`, what does each `typeof` produce?
The first is the JavaScript operator. It runs at runtime and produces one of a fixed set of strings such as `"string"` or `"object"`. The second is TypeScript's type query. It runs only at compile time and produces the full static type of `value`, then disappears from the emitted JavaScript.
Why does `type Keys = keyof handlers;` fail when `handlers` is a `const` object, and what is the fix?
`keyof` operates on types, and `handlers` is a value. TypeScript reports that `handlers` refers to a value but is being used as a type. Writing `keyof typeof handlers` first converts the value to its type with `typeof`, then takes that type's keys.
Why might a generic function constrained with `K extends keyof T` need `string & K` before putting `K` into a string template type?
`keyof T` can include `number` and `symbol` keys as well as strings, so `K` isn't guaranteed to be a string. Intersecting with `string` keeps only the string keys, which is what a string template needs.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.