2
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'

Matan Gubkin
  • 3,019
  • 6
  • 25
  • 44
  • [Please replace/supplement images of code/errors with plaintext versions.](https://meta.stackoverflow.com/a/285557/2887218) – jcalz Jun 01 '22 at 14:57

1 Answers1

2

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?

Jap Mul
  • 17,398
  • 5
  • 55
  • 66