Skip to content
jshacks.dev
TypeScript

keyof and typeof in TypeScript

keyof turns an object type into a union of its keys, and typeof turns a value into its type. Learn each operator, how they combine and where they mislead.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, Vite, npm and JavaScript logos.

Two operators do most of the work of keeping types and values in step. The keyof operator takes an object type and produces the union of its property names. The typeof operator, used in a type position, takes a value and produces its type. Used together they let a single object define both a runtime table and the type of its keys, which removes a whole category of lists that have to be edited twice. This post explains each operator on its own, the combination keyof typeof, the derived types you can build from them, and the points where the two operators surprise people, including the fact that typeof means two different things depending on where it is written. It uses TypeScript 6.x, and the references are the handbook pages on keyof types and typeof types.

keyof on an object type

keyof T evaluates to a union of string literal types, one per property of T. It exists only in the type system, and it is what lets a type say "any key of this object".

keyof-user.tsTypeScript
interface User {
  id: number;
  name: string;
  email: string;
}

type UserKey = keyof User;

const ok: UserKey = "email";
const bad: UserKey = "phone";
Text
keyof-user.ts(10,7): error TS2322: Type '"phone"' is not assignable to type 'keyof User'.

UserKey is the same as "id" | "name" | "email", and the compiler keeps the name keyof User in its messages. The first assignment passes and the second is rejected. If you add a property to User, UserKey grows by itself, which is the benefit over writing the union by hand.

The usual use is as a constraint on a function parameter, so that a key can be checked against the object it will index.

pluck.tsTypeScript
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
  return items.map((item) => item[key]);
}

const users = [
  { id: 1, name: "Ada", email: "[email protected]" },
  { id: 2, name: "Grace", email: "[email protected]" },
];

console.log(pluck(users, "name"));
console.log(pluck(users, "id"));
Text
[ 'Ada', 'Grace' ]
[ 1, 2 ]

The return type follows the key. For "name" the result is string[], and for "id" it is number[]. A third call with "phone" would be rejected at the call site, with the legal keys listed in the message. The T[K] in the signature is an indexed access type, covered in the next post.

keyof and index signatures

When an object type has an index signature, keyof follows the signature and not a list of names. A string index signature gives string | number, because JavaScript converts numeric keys to strings, so both are valid ways to index.

dict.tsTypeScript
type Dict = { [key: string]: number };

const k: keyof Dict = true;
Text
dict.ts(3,7): error TS2322: Type 'boolean' is not assignable to type 'string | number'.

This matters when you apply keyof to a type you did not write. A Record<string, number> has no named keys at all, and a function constrained by K extends keyof T will accept any string for it. If you expected a closed set of keys, check the type you are indexing.

typeof in a type position

In a type position, typeof value produces the static type of a variable or property. This lets you write a value once and reuse its shape as a type.

configure.tsTypeScript
const defaults = { host: "localhost", port: 8080, debug: false };

type Settings = typeof defaults;

export function configure(patch: Partial<Settings>): Settings {
  return { ...defaults, ...patch };
}

console.log(configure({ port: 9000 }));
Text
{ host: 'localhost', port: 9000, debug: false }

Settings is { host: string; port: number; debug: boolean }, taken from the object. There is no separate interface to keep in step, and Partial<Settings> allows any subset of the properties. The compiler enforces the types on the patch.

configure-bad.tsTypeScript
import { configure } from "./configure.js";

configure({ port: "9000" });
Text
configure-bad.ts(3,13): error TS2322: Type 'string' is not assignable to type 'number'.

The type of port came from the literal 8080 in the original object, widened to number.

Two meanings of typeof

The word typeof is shared by two operators. In an expression, it is the JavaScript operator that returns a string such as "number". In a type position, it is the TypeScript operator described above. Context decides which one you get.

two-typeofs.tsTypeScript
const defaults = { host: "localhost", port: 8080, debug: false };

const runtimeKind = typeof defaults.port;
type PortType = typeof defaults.port;

const port: PortType = 3000;

console.log(runtimeKind, port);
Text
number 3000

The first typeof runs and yields the string "number". The second exists only at compile time and names the type number, which is why port can be assigned a number. Only the first one appears in the emitted JavaScript. A typeof in a type position accepts identifiers and property paths, and nothing computed, so typeof makeThing() is not allowed. To get the type that a call would return, use ReturnType<typeof makeThing>.

make-user.tsTypeScript
function makeUser(name: string) {
  return { id: 1, name };
}

type User = ReturnType<typeof makeUser>;

const good: User = { id: 2, name: "Ada" };
const bad: User = { id: "x", name: "Ada" };
Text
make-user.ts(8,21): error TS2322: Type 'string' is not assignable to type 'number'.

The function's return type was never written, and User was derived from what the body returns. If you later add a field to the returned object, User gains it.

Combining them: keyof typeof

A runtime object often is the list of valid names. keyof typeof turns its keys into a type.

hex.tsTypeScript
const palette = { red: "#f00", green: "#0f0" };

export function hex(color: keyof typeof palette): string {
  return palette[color];
}

console.log(hex("red"));
console.log(hex("green"));
Text
#f00
#0f0

The parameter type is "red" | "green". Adding blue: "#00f" to the object extends the accepted names without any other edit. A call with a name that is not in the table is rejected, and the message lists the real options.

hex-bad.tsTypeScript
import { hex } from "./hex.js";

hex("blue");
Text
hex-bad.ts(3,5): error TS2345: Argument of type '"blue"' is not assignable to parameter of type '"red" | "green"'.

The precedence is the point to remember: keyof typeof palette reads as keyof (typeof palette). First the type of the value is taken, then its keys.

Deriving a union of values

A frequent pattern replaces an enum with a constant object. With as const, the object's values are literal types, and indexing its type with its own keys gives a union of the values.

roles.tsTypeScript
export const Roles = { admin: "ADMIN", editor: "EDITOR" } as const;

export type Role = (typeof Roles)[keyof typeof Roles];

function canPublish(role: Role): boolean {
  return role === Roles.admin || role === Roles.editor;
}

console.log(canPublish(Roles.admin));
console.log(canPublish("EDITOR"));
Text
true
true

A value outside the union is rejected.

roles-bad.tsTypeScript
import type { Role } from "./roles.js";

const r: Role = "owner";
Text
roles-bad.ts(3,7): error TS2322: Type '"owner"' is not assignable to type '"ADMIN" | "EDITOR"'.

The constant object gives you a value you can iterate and import, and Role gives you the type, from one definition.

Where the pair misleads

keyof returns the keys the type declares, not the keys that exist at runtime. An object with extra properties, which TypeScript allows when it comes through a variable and not a literal, has more keys than keyof lists. Looping with Object.keys(obj) gives string[], not Array<keyof T>, for that reason, and casting it is a promise rather than a fact.

typeof on a variable that was declared with let gives the widened type, and on a const object it gives the widened property types unless you wrote as const. When the narrow type is what you want, add as const to the value, and the derived types become literals.

Finally, both operators describe the state of the code at compile time, so they cannot detect data that disagrees with the types. A key received from user input is a string, and you must check it against the known keys before using it as a keyof value.

is-key.tsTypeScript
const palette = { red: "#f00", green: "#0f0" };

function isColor(name: string): name is keyof typeof palette {
  return Object.hasOwn(palette, name);
}

for (const input of ["red", "toString"]) {
  console.log(input, isColor(input));
}
Text
red true
toString false

The guard uses Object.hasOwn so that inherited names such as toString are rejected. A plain name in palette check would accept it. Type guards of this form are the subject of an earlier post in the series.

Testing derived types

Types derived from values stay correct only if the value stays the source of truth. A short compile-time test pins the relationship: assign a literal to the derived type and fail the build if the key set changes unexpectedly.

palette.test.tsTypeScript
const palette = { red: "#f00", green: "#0f0" };

type Color = keyof typeof palette;

const colors: Color[] = ["red", "green"];

console.log(colors.length);
Text
2

If someone removes green from the object, the array literal no longer compiles, and the test fails during the type check.

Share

Keep reading

Flat illustration of two options weighed side by side, with the TypeScript, Node.js, npm and JavaScript logos.
TypeScript

Type Annotations vs Type Assertions

A type annotation asks the compiler to check a value, while an assertion tells it to trust you. Learn the difference, the errors and safer alternatives.

6 min read
Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.