Creating a union from an object using TypeScript

Map over the entries of an object to create a new union
15 September 2022
Web development

TL; DR

Accessing the properties of the object, using [keyof typeof object] will access each member of the object in the form of a union.

const values = {
  propA: 'test',
  propB: 123,
} as const

type UnionOfValues =
  typeof values[keyof typeof values]
// UnionOfValues = "test" | 123

This is particularly handy when you want to build new types from an object. We make another object with the same keys, but transform the values to whatever format we need. Then we pluck them out, ignoring our keys:

const values = {
  propA: 'test',
  propB: 123,
} as const

type TransformedWithObjectValues =
    { [K in keyof typeof values]: `${K}:${typeof values[K]}` }[keyof typeof values]
// TransformedWithObjectValues = "propA:test" | "propB:123"

We can also use the key of the new object to do our transformation, then convert the object to a union via keyof

const values = {
  propA: 'test',
  propB: 123,
} as const

type TransformedWithObjectKeys =
  keyof {[K in keyof typeof values as `${K}:${typeof values[K]}`]: K};
// TransformedWithObjectKeys = "propA:test" | "propB:123"