How to convert object values in 2-depth to typescript union without using `String` indexing?

Viewed 39
// from
const obj = {
  a: {
    aa: 'A',
    cc: 'C',
  },
  b: {
    bb: 'B',
    cc: 'C',
  }
} as const;

// to
type ObjValue = 'A' | 'B' | 'C';

Hi, I want to get union type from object.

So I tried with typeof obj[keyof typeof obj] pattern, but it just returns this.

type ObjValue = 'C'

How do I get the union type composed only string values of object without String indexing?

1 Answers

I am not sure why the typeof obj[keyof typeof obj] pattern does not really work with unions. Using mapped types solves the problem though.

type ObjValue = {
  [K in keyof typeof obj]: typeof obj[K][keyof (typeof obj[K])]  
}[keyof typeof obj]

// type ObjValue = "A" | "C" | "B"

Playground

Related