TypeScript keyof and typeof: Object Type Queries and Property Keys
The difference between the two type queries, why keyof typeof collapses to string without literal types, and how K extends keyof T keeps a key and its value type in correspondence.

keyof and typeof answer two different questions that meet in the same expression: typeof reads the type of a value, and keyof reads the keys of a type. Together, keyof typeof obj turns a runtime object into a union of its property names, which is the standard way to keep a string-keyed map, a lookup function, and its call sites in agreement without duplicating the key list by hand.
Quick Summary
typeofin a type position refers to a value declaration;typeof xoutside a type position is the JavaScript runtime operator, and the two are unrelated.keyof Tis the union of the keys ofT— for a string-keyed object it is a union of literals, for an index signature it isstring | number.keyof typeof objrequiresobjto be aconst-like value with narrow literal types; withoutas constor a literal declaration, the keys widen and the union collapses tostring.T[K]is an indexed access type;Kmust be assignable tokeyof T, which is what makesobj[key]type-safe inside a generic function.keyof anyisstring | number | symbol,keyof {}isnever, andkeyof neverisstring | number | symbol— edge cases that appear in constraint logic.keyofover a union produces the intersection of the keys (only the keys present on every member), which is often the opposite of what was intended.- Since TypeScript 4.4, a symbol or template literal key appears in
keyofwith its literal type, and mapped types overkeyofpreserve it.
Basic syntax and type signatures
interface User {
id: number;
name: string;
email: string | null;
}
type UserKey = keyof User; // "id" | "name" | "email"
type IdType = User["id"]; // number
type AnyValue = User[UserKey]; // number | string | null
// typeof reads the type of a value.
const defaults = { retries: 3, timeoutMs: 5_000 };
type Defaults = typeof defaults; // { retries: number; timeoutMs: number }
// Combining them recovers a union of the declared keys.
const defaultsLiteral = { retries: 3, timeoutMs: 5_000 } as const;
type DefaultKey = keyof typeof defaultsLiteral; // "retries" | "timeoutMs"
// A generic accessor keeps key and value in correspondence.
function get<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const id = get({ id: 1, name: "ada" }, "id"); // number
// get({ id: 1 }, "name"); // error: "name" is not a key
// `keyof any` is the constraint that accepts any property key.
function pluck<T, K extends keyof any>(obj: T, keys: K[]) { /* ... */ }The K extends keyof T constraint plus the T[K] return type is the pattern behind Pick, Omit, pluck, groupBy, and nearly every typed ORM helper. It works because the compiler can prove that obj[key] is exactly T[K] for the specific key the caller passed.
Comparison of the query forms
| Form | Question answered | Example | Result |
|---|---|---|---|
typeof value (type position) | what type does this value have | const n = 1 | 1 |
keyof T | which keys does this type have | keyof { a: 1; b: 2 } | "a" | "b" |
keyof typeof obj | keys of a value's type | keyof typeof { a: 1 } as const | "a" |
T[K] | type at a key | { a: 1 }["a"] | 1 |
T[keyof T] | union of all value types | { a: 1; b: "x" }[keyof ...] | 1 | "x" |
keyof (A | B) | keys common to every member | keyof ({a: 1} | {a: 1; b: 2}) | "a" |
keyof (A & B) | keys of the merged shape | keyof ({a: 1} & {b: 2}) | "a" | "b" |
keyof string | own keys of the type, method names included | — | number | "toString" | ... |
The union row is the one most often misread: keyof (A | B) is keyof A & keyof B, because a value of the union type may be either member and only the shared keys are safe to read.
Practical edge cases and deep dives
1. Keeping a runtime key list and its type in sync
const SORT_FIELDS = ["createdAt", "title", "relevance"] as const;
type SortField = (typeof SORT_FIELDS)[number]; // "createdAt" | "title" | "relevance"
interface Post {
title: string;
body: string;
createdAt: Date;
}
// Ensure every sortable field is actually a property of Post.
const _check: Record<SortField, keyof Post> = {
createdAt: "createdAt",
title: "title",
relevance: "id", // add "id" to Post or this line errors
};
function sortPosts(posts: Post[], by: SortField): Post[] {
return [...posts].sort((a, b) => {
if (by === "relevance") return 0;
const av = a[by];
const bv = b[by];
return av < bv ? -1 : av > bv ? 1 : 0;
});
}Two checks are doing different work. SortField is derived from the array, so adding a value to the array immediately widens the union and breaks exhaustive switches elsewhere. The Record<SortField, keyof Post> annotation proves each field name exists on the entity, which is the assertion keyof cannot make on its own because the two live in different modules. The comparison av < bv also compiles only because a[by] narrows to Date | string; relevance was excluded by the early return.
2. keyof across an index signature and a union
interface StringMap {
[key: string]: number;
}
type K1 = keyof StringMap; // string | number
// Numeric index signatures add `number` to the key union.
interface ArrayLike {
[index: number]: string;
length: number;
}
type K2 = keyof ArrayLike; // number | "length"
// Union types intersect their keys.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
type SharedKeys = keyof Shape; // "kind"
// To get the union of all keys, distribute first.
type AllKeys<T> = T extends unknown ? keyof T : never;
type EveryKey = AllKeys<Shape>; // "kind" | "radius" | "side"keyof StringMap being string | number is not a quirk: JavaScript coerces numeric property access to strings, so the compiler admits both. The distribution helper AllKeys is the standard repair for the union case, and it works because the conditional type distributes over the naked type parameter.
3. Typed property access on a Record with a subset of keys
type Metrics = Record<"requests" | "errors" | "latencyMs", number>;
function increment<K extends keyof Metrics>(m: Metrics, key: K, by = 1): void {
m[key] += by; // ok: m[key] is number for every K
}
// A helper that reads several keys returns a precise object type.
function pickM<T, K extends keyof T>(obj: T, keys: readonly K[]): Pick<T, K> {
const out = {} as Pick<T, K>;
for (const key of keys) out[key] = obj[key];
return out;
}
const summary = pickM({ a: 1, b: "x", c: true }, ["a", "c"] as const);
// { a: number; c: boolean }Writing acc[key] = value inside a generic function fails with Type 'T[K]' is not assignable to type 'never' when the accumulator is typed {} or Partial<T>, because assignment to an indexed access with a still-generic key is unsound from the compiler's point of view. The as Pick<T, K> assertion on an empty object is the accepted workaround, and it is safe here because the loop assigns every key in keys exactly once.
4. Symbol keys and keyof with explicit unique symbol
const brand = Symbol("brand");
type Branded = {
[brand]: "user";
id: number;
};
type K = keyof Branded; // typeof brand | "id"
function has<T, K extends PropertyKey>(obj: T, key: K): obj is T & Record<K, unknown> {
return key in (obj as object);
}
if (has(value, brand)) {
value[brand]; // "user", narrowed
}Since 4.4 a unique symbol key appears in keyof as that symbol type and can be narrowed by an in check. This is how nominal branding is done without a runtime tag: the symbol is not exported from the module, so no other module can build the branded type by hand, and keyof still lists the key for mapped types.
5. typeof on imports, classes, and functions
import { createClient } from "./client";
type Factory = typeof createClient; // the function type
type Returned = Awaited<ReturnType<typeof createClient>>;
class Store { open() {} }
type StoreInstance = InstanceType<typeof Store>; // Store
// `typeof` with an enum has the enum object's type, not a member's type.
enum Level { Debug, Info }
type LevelObject = typeof Level; // { Debug: Level.Debug; Info: Level.Info }
type Member = typeof Level.Debug; // Level.Debugtypeof in a type position only sees declarations visible at that point, which is why typeof someFunction after an import requires the import to be a value import and not import type. A class name in a type position is the instance type; typeof ClassName is the constructor.
Common mistakes and compiler errors
| Error or symptom | Cause | Fix |
|---|---|---|
'keyof' cannot be used as a value | keyof placed in a value expression | move the query into a type annotation |
'X' is declared but its value is never read after typeof | typeof type query on a value that is otherwise unused | keep the value as the source of truth, or write the type explicitly |
keyof typeof obj is string | obj was not declared as const or with literal members | assert the object or declare an explicit const object |
Type 'string' cannot be used to index type 'T' | the key parameter is not constrained by keyof T | add K extends keyof T |
Property 'x' does not exist on type 'A | B' | keyof on a union gives only shared keys | distribute with T extends unknown ? keyof T : never |
Type 'T[K]' is not assignable to type 'never' when assigning into an accumulator | generic indexed assignment | assert the accumulator type or use Object.fromEntries |
keyof T includes methods of string | keyof string includes the prototype's members | narrow with a template literal or use keyof T & string |
typeof sees only a widened type | the query was placed on a value inferred too broadly | declare the literal, or use as const and typeof together |
The reliable habit is to make one declaration the source of truth and derive everything else from it: the object literal for its shape, the array literal for its members, the concrete type for its keys. keyof typeof is the bridge that makes a value serve as the source of a type, and it only keeps its precision when the value itself keeps literal types.
Try matching browser tools
All toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesTypeScript Generic Parameter Defaults: Syntax, Precedence, and Inference
When a default applies and when inference wins, defaults that reference earlier parameters, and how a defaulted type parameter keeps a library change non-breaking.
TypeScript Branded Types: Nominal Typing, Type Tags, and Validation
How a phantom property makes two strings incompatible, unique symbol brands, unit-typed numbers, and the places where a brand quietly disappears.
TypeScript Ambient Declarations: .d.ts Files, declare, and declare global
How declare and .d.ts files describe runtime values, wildcard modules for assets, declare global with var, and module augmentation of third-party types.
TypeScript Discriminated Unions: Exhaustiveness Checking and the never Type
Why the discriminant must be a literal, how never closes an exhaustive switch, and the duplicate-discriminant bug that lets a missing case compile.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.