Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readTypeScript
#TypeScript#Type System#Generics
3D illustration of JavaScript object key tags being scanned into a type-safe union key ring labelled with property names

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

  • typeof in a type position refers to a value declaration; typeof x outside a type position is the JavaScript runtime operator, and the two are unrelated.
  • keyof T is the union of the keys of T — for a string-keyed object it is a union of literals, for an index signature it is string | number.
  • keyof typeof obj requires obj to be a const-like value with narrow literal types; without as const or a literal declaration, the keys widen and the union collapses to string.
  • T[K] is an indexed access type; K must be assignable to keyof T, which is what makes obj[key] type-safe inside a generic function.
  • keyof any is string | number | symbol, keyof {} is never, and keyof never is string | number | symbol — edge cases that appear in constraint logic.
  • keyof over 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 keyof with its literal type, and mapped types over keyof preserve it.

Basic syntax and type signatures

typescript
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

FormQuestion answeredExampleResult
typeof value (type position)what type does this value haveconst n = 11
keyof Twhich keys does this type havekeyof { a: 1; b: 2 }"a" | "b"
keyof typeof objkeys of a value's typekeyof 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 memberkeyof ({a: 1} | {a: 1; b: 2})"a"
keyof (A & B)keys of the merged shapekeyof ({a: 1} & {b: 2})"a" | "b"
keyof stringown 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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
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.Debug

typeof 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 symptomCauseFix
'keyof' cannot be used as a valuekeyof placed in a value expressionmove the query into a type annotation
'X' is declared but its value is never read after typeoftypeof type query on a value that is otherwise unusedkeep the value as the source of truth, or write the type explicitly
keyof typeof obj is stringobj was not declared as const or with literal membersassert 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 Tadd K extends keyof T
Property 'x' does not exist on type 'A | B'keyof on a union gives only shared keysdistribute with T extends unknown ? keyof T : never
Type 'T[K]' is not assignable to type 'never' when assigning into an accumulatorgeneric indexed assignmentassert the accumulator type or use Object.fromEntries
keyof T includes methods of stringkeyof string includes the prototype's membersnarrow with a template literal or use keyof T & string
typeof sees only a widened typethe query was placed on a value inferred too broadlydeclare 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 tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.