keyof and typeof

Topic 1 of 6 in Type operators7 min readIntermediateFree course

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.

Moving between values and types. In the value world, which runs, there is const config = { port: 8080, host: “localhost” }. In the type world, which is erased, typeof config is { port: number; host: string } and keyof typeof config is “port” | “host”. typeof (in a type position) turns a value into its type. keyof turns an object type into a union of its keys. Together they keep types in sync with real data — change the object and the types follow.

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”:

TypeScript
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

TypeScript
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:

TypeScript
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:

TypeScript
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, keyof gives the index type: keyof { [key: string]: number } is string | number (because obj[1] also works on objects). Oddly, keyof Record<string, number> is just string — it’s built as a mapped type rather than an index signature.
  • keyof of an array type includes number and all the array methods’ names — rarely useful.
  • keyof of 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:

TypeScript
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:

TypeScript
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: typeof goes from values to types; keyof goes from object types to their keys; keyof typeof obj gets the keys of a real object.

Exercise

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.

TypeScript
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–5

Summary

  • typeof value in a type position gives the type TypeScript inferred for that value.
  • keyof Type gives a union of an object type’s property names.
  • keyof typeof obj gets the keys of a real object — handy for lookup tables and as const data.
  • ReturnType<typeof fn> and Parameters<typeof fn> derive types from functions.
  • Deriving types from values means one source of truth: change the data and the types follow.