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

Top comments (0)