Andrew's Digital Garden

Using keyof typeof in Typescript

This combination is useful to take a JS object and turn it into a literal union type, based on the object's keys.

const dataObj = { x: 'foo', y: 1 }; type Data = typeof dataObj; // { x: string, y: number } type DataKeys = keyof Data; // "x" | "y" // or type Keys = keyof typeof dataObj;

You can also get a type based on the object's values:

const dataObj = { x: 'foo', y: 1 }; type Values = (typeof dataObj)[keyof typeof dataObj];

[[js]] [[ts]]

Using `keyof typeof` in Typescript