keyof and typeof in TypeScript: how do they work?
IntermediateTypeScript interview questionBy UIRound, updated 17 November 2026
Short answer
keyof T produces a union of the property names of an object type, so keyof { id: number; name: string } is "id" | "name". typeof x in a type position gives you the type TypeScript inferred for a value, which is different from JavaScript's runtime typeof that returns a string. Together, keyof typeof obj turns a real object into a union of its keys, and T[K] reads the type of a property.
keyof: the keys of a type
keyof works on types, never on values. It returns a union of string, number or symbol literal types, one for each known property.
type User = { id: number; name: string; email?: string };
type UserKey = keyof User; // "id" | "name" | "email"
type Dict = { [key: string]: boolean };
type DictKey = keyof Dict; // string | numberOptional properties are still keys, so "email" is in the union. With a string index signature you get string | number, because JavaScript turns numeric keys into strings, so dict[1] is also allowed. keyof any is string | number | symbol, which is why you often see K extends PropertyKey in library code.
On combined types the result can surprise you. keyof (A | B) gives only the keys the two types share, because a value of the union is only guaranteed to have those. keyof (A & B) gives every key of both. The reasoning is in union vs intersection types.
typeof: two different operators with one name
In an expression, typeof is the JavaScript operator. It runs at runtime and returns a string such as "object" or "number". In a type position, after type X = or a colon, typeof is a TypeScript type query. It runs at compile time and returns the static type of a variable or property.
const config = { apiUrl: "https://api.example.com", retries: 3, debug: false };
console.log(typeof config); // runtime: the string "object"
type Config = typeof config; // compile time: { apiUrl: string; retries: number; debug: boolean }
type Retries = typeof config.retries; // numberThe type query only accepts identifiers and property access. typeof createUser("x") is an error, because TypeScript will not evaluate a call. Write ReturnType<typeof createUser> to get the type of what a function returns. Runtime typeof is also how you narrow unknown values, which is covered in type narrowing.
keyof typeof: keys of a real object
keyof needs a type and typeof turns a value into one, so the two compose. This is the standard way to keep a type in sync with a runtime object you already have.
const routes = { home: "/", account: "/account", settings: "/settings" } as const;
type RouteName = keyof typeof routes; // "home" | "account" | "settings"
type RoutePath = (typeof routes)[RouteName]; // "/" | "/account" | "/settings"
function isRouteName(key: string): key is RouteName {
return Object.hasOwn(routes, key);
}Read keyof typeof routes right to left: take the value routes, get its type, then get that type's keys. Add a route to the object and both types update. Without as const, RoutePath would widen to string, because ordinary object properties are inferred as their general type. What does as const do explains the widening.
Indexed access types: T[K]
Square brackets on a type read the type of a property, just as they read a value at runtime. The index can be a single key, a union of keys, or number for array elements.
type Name = User["name"]; // string
type IdOrName = User["id" | "name"]; // number | string
type AnyValue = User[keyof User]; // number | string | undefined
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"T[keyof T] gives the union of all value types. (typeof arr)[number] gives the union of the element types, which is the usual way to derive a union from a list. The parentheses around typeof ROLES are not always required, but they make the precedence obvious to a reader.
Putting it together in a generic
The most common interview example is a typed property getter. K extends keyof T restricts the key to real property names, and T[K] makes the return type follow the key that was passed.
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const id = getProp({ id: 1, name: "Ada" }, "id"); // number
getProp({ id: 1 }, "nope"); // error: '"nope"' is not assignable to '"id"'The same two pieces power typed pick, typed event emitters (on<E extends keyof Events>(event: E, handler: (payload: Events[E]) => void)) and typed form libraries. What are generics covers constraints in more depth, and mapped types build on keyof to transform every property at once.
Practise it
Start with Derive types from a config object with keyof, typeof, as const and indexed access, then make return types follow the keys in Type pick and omit functions and Type Object.keys, Object.entries and Object.fromEntries helpers. For harder practice, Type an event emitter and Implement Get<T, Path> use indexed access in generics.
Common follow-up questions
Why does Object.keys return string[] and not (keyof T)[]?
Object types in TypeScript are open: a value of type User may carry extra properties that the type does not mention. Returning (keyof User)[] would be a lie for those objects, so the standard library returns string[]. If you control the object, cast with Object.keys(obj) as (keyof typeof obj)[] and accept that trade-off knowingly.
What is the difference between keyof and Object.keys?
keyof exists only at compile time and produces a type. Object.keys runs at runtime and produces an array of strings. Neither knows about the other, which is why you derive types from values with typeof and not the other way round.
Can I use typeof on a function call or an expression?
No. The type query works on names and property paths only. For a function's return type use ReturnType<typeof fn>, for its parameters Parameters<typeof fn>, and for a class instance InstanceType<typeof MyClass>.
Why does keyof on a union give fewer keys?
A value of A | B might be either type, so only keys present in both are safe to access. To get every key from every member, distribute over the union with a conditional type such as T extends unknown ? keyof T : never.
Mistakes to avoid
Writing
keyof objon a valuekeyofneeds a type, so writekeyof typeof obj.Forgetting
as constand gettingstringwhere you expected a union of literal valuesConfusing runtime
typeof x === "object"checks with the compile-time type queryTyping a lookup parameter as
stringand indexing an object with it, then silencing the error withanyinstead of usingkeyof typeofAssuming
(keyof T)[]fromObject.keysis always safe when the object can have extra properties
Sources
Practise it in code
Interviewers rarely stop at the definition. These questions open in an editor with tests.
- Derive types from a config object with
keyof,typeof,as constand indexed accessEasy15 min - Type
pickandomitfunctions whose return types follow the keys passed inMedium20 min - Type
Object.,keys Object.andentries Object.helpers that keep their key typesEasy25 minfromEntries - Type an event emitter so on and emit only accept known events and their payloadsHard50 min
- Implement Get<T, Path> to read a nested property type by a dot pathMedium40 min