keyof and indexed access
type Key = keyof Point;
type Value = Point["x"];
type Either = Point["x" | "y"];
type Shared = keyof (A | B);
type All = keyof (A & B);Take the keys of a type, or the type of one or more properties. keyof on a union keeps only shared keys.
| Type parameter | Description |
|---|---|
T | The object (or array or tuple) type to read keys or properties from. |
K | A key, a union of keys, number for an array element, or a tuple index. A key that is not in T is a type error. |
Produces: A union of keys, or the type of the selected properties. For an optional property, the result includes undefined under default --strict.
Type errors
type error— Indexing with a key that does not exist on the type is a type error. Assigning a key that is not in keyof T is also a type error.
- These examples do not rewrite Record, which is a mapped type over a key union and stays on the Record page.
type Point = { x: number; y: number };
type Key = keyof Point;
const key: Key = "x";
const value: Point["x"] = 1;
const either: Point["x" | "y"] = 2;
// @ts-expect-error "z" is not a key of Point
const missing: Point["z"] = 1;
// @ts-expect-error "z" is not in keyof Point
const badKey: Key = "z";
type Optional = { a?: string };
const maybe: Optional["a"] = undefined;
type A = { a: string; c: number };
type B = { b: boolean; c: number };
const shared: keyof (A | B) = "c";
const all: keyof (A & B) = "a";
// @ts-expect-error "a" is not in every member of the union
const notShared: keyof (A | B) = "a";
const item: string[][number] = "ok";
console.log(key, shared, item);Expected output
x c ok