How can I achieve a union type of object values in typescript

Viewed 112
const obj = {
    a: 122,
    b: 456,
    c: '123',
};

// Keys = "a" | "b" | "c"
type Keys = keyof typeof obj;
// Values = string | number"
type Values = typeof obj[Keys];
const a: Values = '1234'; // => should throw an error

I am looking for a way to get a union type like so: 123 | 456 | '123'

1 Answers

Using a combination of as const, keyof and typeof you can achieve this. With as consts the object becomes immutable and Typescript is able to extract the values using the keys.

const obj = {
  a: 122,
  b: 456,
  c: '123',
} as const // use 'as const' here

// Keys = "a" | "b" | "c"
type Keys = keyof typeof obj
// Values = 122 | 456 | "123"
type Values = typeof obj[Keys]

This is a nice explanation of the as const functionality btw: What does the "as const" mean in TypeScript and what is its use case?

Related