TypeScript ยท Chapter 34 of 44

TypeScript keyof and typeof Operators

The `keyof` operator produces a union of all the property names (as string literal types) of a given type. It's useful for writing functions that safely access any property of an object.

The `typeof` operator, when used in a type context, extracts the type of a variable or value, letting you reuse an inferred type without writing it out manually again.

Syntax
type UserKeys = keyof User;
type ConfigType = typeof config;

keyof

For `interface User { name: string; age: number }`, `keyof User` produces the type `"name" | "age"`, a union of all property name literals.

typeof in type positions

Writing `typeof someVariable` inside a type annotation captures the exact inferred type of that variable, which is handy for deriving types from existing values.

Example 1 (typescript)
interface User {
  name: string;
  age: number;
}
function getProp(user: User, key: keyof User) {
  return user[key];
}
const u: User = { name: "Lin", age: 27 };
console.log(getProp(u, "name"));
Output
Lin

keyof User restricts key to only valid property names of User, catching typos at compile time.

Example 2 (typescript)
const config = { host: "localhost", port: 8080 };
type Config = typeof config;
const other: Config = { host: "example.com", port: 3000 };
console.log(other);
Output
{ host: 'example.com', port: 3000 }

typeof config captures the object's inferred shape as a reusable type.

Key points

  • keyof produces a union of a type's property names as string literals.
  • keyof is often used to safely restrict function parameters to valid keys.
  • typeof, in a type position, extracts the type of an existing variable.
  • Both operators help you derive new types from existing code instead of duplicating them.
๐Ÿ’ก Note: keyof and typeof are frequently combined, such as `keyof typeof someObject`, to get the keys of a plain object's inferred type.

๐Ÿ“ Quick Quiz

1. What does `keyof User` produce for an interface with name and age?

2. What does `typeof` do in a type position?

3. Why use keyof for a function parameter?