Skip to content
Search

TypeScript:keyof

lastmod 2023-06-09created 2022-12-154 edits

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

Simple example

The type P below is the same type as "x" | "y".

type Point = { x: number; y: number };
type P = keyof Point;

If the type has a string or number index signature, keyof returns those types instead.

type Arrayish = { [n: number]: unknown };
type A = keyof Arrayish;

type Mapish = { [k: string]: boolean };
type M = keyof Mapish;

Note that in the example above, M is string | number. - This is because JavaScript object keys are always coerced to a string, so obj[0] is the same as obj["0"].

keyof types become especially useful when combined with mapped types, which we'll learn more about later.

How to iterate over keys

Object.entries(obj).forEach(
  ([key, value]) => console.log(key, value)
);

See also

Favorite site

author Zer0 sitemap