What do the typeof and keyof operators do in the type system?
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
typeof converts a *value* (variable/function) into its type at the type level. keyof produces a union of an object type's keys. Combined they let you derive precise types from existing code instead of duplicating definitions.
Detailed explanation
In type positions, typeof config gives you the type of the config value — perfect when implementation already encodes the shape: export type Config = typeof DEFAULT_CONFIG keeps types in lockstep with reality. typeof also captures overloaded function signatures. keyof User resolves to 'id' | 'name' | 'email' — the set of valid keys — enabling type-safe property access: function get<T, K extends keyof T>(obj: T, key: K): T[K]. Note T[K] — indexed access — pairs naturally with keyof to express 'the type of that specific property.' Chaining these powers real utilities: Pick<T, keyof T> is identity; omitting keys becomes Omit; event maps map handler names via template literals over keyof. The distinction trips people because typeof exists at runtime too — in type annotations it's purely compile-time and erased afterward.
Example
const ROLES = { admin: 1, editor: 2, viewer: 3 } as const;
type RoleName = keyof typeof ROLES; // 'admin' | 'editor' | 'viewer'
type RoleValue = (typeof ROLES)[RoleName]; // 1 | 2 | 3
function get<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: 'Ada' };
get(user, 'name'); // string — precisely inferredInterview tip
Emphasize directionality — typeof lifts values into types, keyof extracts keys from types — then show the as-const + keyof typeof idiom, beloved in interviews.
Common mistakes
- Confusing type-level typeof with runtime typeof.
- Forgetting
as constwhen deriving literal unions from objects.