The keyof and typeof operators are powerful typing tools in TypeScript. Their combined use allows for on-the-fly type construction, creating safe functions and expressing object structures as flexibly as possible.
typeof in TypeScript is used to infer a type from a variable, while keyof returns a union of all keys of an object or type. Together, they enable working with dynamically declared objects and creating interrelated types.
Without these operators, when working with objects, enums, and lookup tables, you often have to manually repeat key strings in types and values, leading to desynchronization errors and complicating code maintenance.
Using typeof, you obtain the type from the value of a variable, and with keyof, you construct a union type of all its keys. The result is type automation.
Code example:
const ERRORS = { NOT_FOUND: 'Not found', UNAUTHORIZED: 'Unauthorized', SERVER_ERROR: 'Server error', }; // Using typeof to get the type, and keyof to get all keys of the object function getErrorMessage(code: keyof typeof ERRORS): string { return ERRORS[code]; }
Key features:
Can values of an object obtained through typeof automatically become keys in a union type?
No, typeof returns the type structure of the object, not the values. To obtain a union of values, you must separately infer the value types.
What does typeof return for enum and what does keyof typeof return for enum?
For enum, typeof returns the type of the enum object (with both directions: key-value and value-key), while keyof typeof provides a union of string/numeric keys of that object. For example:
enum Colors { Red = 'R', Blue = 'B' } type ColorKeys = keyof typeof Colors; // 'Red' | 'Blue'
Can you get a type-safe list of all possible parameters of a function that takes object keys using keyof typeof?
Yes, this way you create a function that only accepts valid keys. This prevents errors when working with object keys.
const config = { mode: 'dark', lang: 'ru' }; type ConfigKeys = keyof typeof config; // 'mode' | 'lang' function useConfig(key: ConfigKeys) { // ... }
keyof typeof applies to array values— for an array, this is indices, not values.typeof operates at the type level, not returning a runtime value.In a constant with API statuses, string key types are manually defined:
type StatusCodes = 'OK' | 'FAIL' | 'PENDING'; function isKnownStatus(code: StatusCodes) { /* ... */ }
Pros:
Cons:
Using keyof typeof for automatic support of the list:
const STATUS = { OK: 1, FAIL: 0, PENDING: 2 }; type StatusKeys = keyof typeof STATUS; function checkStatus(key: StatusKeys) { /* ... */ }
Pros:
Cons: