Lesson 25 +10 XP

keyof & typeof Operators

keyof & typeof Operators

TypeScript provides type-level operators to inspect object shapes and infer types from existing runtime values.

The keyof Operator

The keyof operator takes an object type and produces a string or numeric literal union of its keys.

interface Person {
  name: string;
  age: number;
  location: string;
}

type PersonKeys = keyof Person; // "name" | "age" | "location"

The typeof Operator in Type Contexts

In type annotations, typeof extracts the TypeScript type of an existing variable or object.

const defaultConfig = {
  host: "localhost",
  port: 8080,
  debug: true
};

type AppConfig = typeof defaultConfig;
/*
Resulting type:
{
  host: string;
  port: number;
  debug: boolean;
}
*/

Combining keyof and typeof

type ConfigKey = keyof typeof defaultConfig; // "host" | "port" | "debug"

TL;DR

  • keyof T returns a union of all property key names of type T.
  • typeof val in a type context extracts the static type of a runtime value.
  • keyof typeof obj gets property key unions directly from JavaScript objects.