DEV Community

kay-adamof
kay-adamof

Posted on

[TypeScript] Creating a literal type union from object values

Let's say you have the following JavaScript object:

const test = {
  a: "hello",
  b: "world",
  c: 0
}
Enter fullscreen mode Exit fullscreen mode

And you want to create a literal type union using the values of this object, namely "hello", "world", and 0.

type TestValues = "hello" | "world" | 0
Enter fullscreen mode Exit fullscreen mode

The answer would be as follows:

const test = {
  a: "hello",
  b: "world",
  c: 0
} as const // <== !!!

type TestValues = (typeof test)[keyof typeof test]
// type TestValues = 0 | "hello" | "world"
Enter fullscreen mode Exit fullscreen mode

Make sure to include as const.

If you forget to add it, the resulting type union would be a union of string and number, rather than the exact literal values.

const test = {
  a: "hello",
  b: "world",
  c: 0
}

type TestValues = (typeof test)[keyof typeof test]
// type TestValues = string | number
Enter fullscreen mode Exit fullscreen mode

By the way, if you want to create a similar type based on the keys of the object instead of the values, you can do it like this:

const test = {
  a: "hello",
  b: "world",
  c: 0
}

type TestKeys = keyof typeof test
// type TestKeys = "a" | "b" | "c"
Enter fullscreen mode Exit fullscreen mode

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay