Let's say you have the following JavaScript object:
const test = { a: "hello", b: "world", c: 0 }
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
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"
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
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"
Top comments (0)