keyof and typeof
Overview
TypeScript has two worlds: the value world — variables, functions, objects that exist when the code runs — and the type world, which is checked and then erased. Two small operators connect them. typeof brings a value’s type into the type world, and keyof turns an object type into the list of its keys. Together they let you write data once and derive the types from it.
typeof in types
JavaScript already has a typeof operator that returns a string at run time (typeof 42 === "number"). TypeScript adds a second use: in a type position, typeof x means “the type of the variable x”:
const config = {
port: 8080,
host: "localhost",
debug: false,
};
type Config = typeof config;
// { port: number; host: string; debug: boolean }
function start(options: Config) { … }You never wrote the Config type by hand. Add a property to config, and Config gains it automatically.
TypeScript tells the two typeofs apart by position: after type X = or a colon, it’s the type operator; in an expression, it’s JavaScript’s.
typeof with functions
function createUser(name: string, admin = false) {
return { id: crypto.randomUUID(), name, admin, createdAt: new Date() };
}
type User = ReturnType<typeof createUser>;
// { id: `${string}-${string}-${string}-${string}-${string}`; name: string; admin: boolean; createdAt: Date }
type CreateUserArgs = Parameters<typeof createUser>;
// [name: string, admin?: boolean]ReturnType and Parameters are utility types (Utility types) that take a function type — which you get with typeof.
typeof with as const
Combined with as const, typeof captures exact values:
const COLORS = ["red", "green", "blue"] as const;
type Color = (typeof COLORS)[number]; // "red" | "green" | "blue"keyof
keyof takes an object type and produces a union of its keys:
type User = { id: number; name: string; email: string };
type UserKey = keyof User; // "id" | "name" | "email"
function pluck(user: User, key: UserKey) {
return user[key];
}
pluck(user, "email"); // ✓
pluck(user, "phone");
// error TS2345: Argument of type '"phone"' is not assignable to parameter of type 'keyof User'.A few details:
- For a type with a string index signature,
keyofgives the index type:keyof { [key: string]: number }isstring | number(becauseobj[1]also works on objects). Oddly,keyof Record<string, number>is juststring— it’s built as a mapped type rather than an index signature. keyofof an array type includesnumberand all the array methods’ names — rarely useful.keyofof a union gives only the keys all members share.
keyof typeof: keys of a real object
keyof works on types, so to get the keys of a value, combine the two:
const ROUTES = {
home: "/",
products: "/products",
cart: "/cart",
};
type RouteName = keyof typeof ROUTES; // "home" | "products" | "cart"
function navigate(route: RouteName) {
location.href = ROUTES[route];
}Read it inside-out: typeof ROUTES is the object’s type; keyof of that is its keys. You saw this in as const and satisfies and Enums and alternatives — now you know how it works.
Putting them together with generics
keyof shines in constraints, as in Generic constraints:
function getSetting<K extends keyof Settings>(settings: Settings, key: K): Settings[K] {
return settings[key];
}The Settings[K] part — looking up a property’s type — is the subject of the next lesson.
Why derive types?
Hand-written types duplicate information that’s already in your code. Duplicates drift: someone adds a route to ROUTES but forgets the RouteName union. Deriving types removes the duplicate:
| Instead of… | Derive it |
|---|---|
writing a Config type next to the config object |
type Config = typeof config |
| listing route names by hand | keyof typeof ROUTES |
| copying a function’s result type | ReturnType<typeof fn> |
| copying an array’s allowed values | (typeof VALUES)[number] |
The opposite also works: sometimes the type is the source of truth (an API contract), and values must conform to it with satisfies. Decide which side is the source, and derive the other.
Remember:
typeofgoes from values to types;keyofgoes from object types to their keys;keyof typeof objgets the keys of a real object.
Settings derived from defaults
Starting from the defaults object (no hand-written types allowed): (1) derive type Settings = typeof defaults and type SettingKey = keyof Settings; (2) write getSetting<K extends SettingKey>(settings: Settings, key: K): Settings[K]; (3) write withChanges(settings: Settings, changes: Partial<Settings>): Settings; (4) write function describe(settings: Settings) that loops over a const list of keys typed SettingKey[] and prints key = value; (5) derive type Summary = ReturnType<typeof summarise> from the provided summarise function and use it to annotate a variable. Show with // @ts-expect-error that getSetting(defaults, "colour") and a fontSize of "14px" are rejected.
const defaults = {
theme: "light",
fontSize: 14,
autosave: true,
language: "en-GB",
};
function summarise(settings: typeof defaults) {
return { dark: settings.theme === "dark", large: settings.fontSize > 16 };
}
// 1–5const defaults = {
theme: "light",
fontSize: 14,
autosave: true,
language: "en-GB",
};
function summarise(settings: typeof defaults) {
return { dark: settings.theme === "dark", large: settings.fontSize > 16 };
}
// 1. Types derived from the value
type Settings = typeof defaults; // { theme: string; fontSize: number; autosave: boolean; language: string }
type SettingKey = keyof Settings; // "theme" | "fontSize" | "autosave" | "language"
// 2. Typed lookup
function getSetting<K extends SettingKey>(settings: Settings, key: K): Settings[K] {
return settings[key];
}
// 3. Partial updates
function withChanges(settings: Settings, changes: Partial<Settings>): Settings {
return { ...settings, ...changes };
}
// 4. Looping over known keys
const KEYS: SettingKey[] = ["theme", "fontSize", "autosave", "language"];
function describe(settings: Settings) {
for (const key of KEYS) console.log(`${key} = ${settings[key]}`);
}
// 5. A type from a function's return value
type Summary = ReturnType<typeof summarise>; // { dark: boolean; large: boolean }
const mine = withChanges(defaults, { theme: "dark", fontSize: 18 });
const size: number = getSetting(mine, "fontSize");
console.log(size); // 18
describe(mine);
const summary: Summary = summarise(mine);
console.log(summary); // { dark: true, large: true }
// @ts-expect-error -- "colour" is not a setting
getSetting(defaults, "colour");
// @ts-expect-error -- fontSize is a number
withChanges(defaults, { fontSize: "14px" });Summary
typeof valuein a type position gives the type TypeScript inferred for that value.keyof Typegives a union of an object type’s property names.keyof typeof objgets the keys of a real object — handy for lookup tables andas constdata.ReturnType<typeof fn>andParameters<typeof fn>derive types from functions.- Deriving types from values means one source of truth: change the data and the types follow.