Home > database >  Extract values from a property in a tuple
Extract values from a property in a tuple

Time:11-10

type A = [{a: 1}, {a: 'x'}]
type TupleToUnion<T, K> = ...

TupleToUnion<A, 'a'> // expected to be `1 | 'x'`

How can I define TupleToUnion?

CodePudding user response:

To get your type, without using generics, you can use this indexed access type

type B = A[number]['a']

The following generic type should be able to emulate the above. First infer the union type of all objects in T (as U) and then index that union with K after asserting that it is valid and extends the available keys

Playground

type A = [{a: 1}, {a: 'x'}]
type TupleToUnion<T, K> = T extends Array<infer U> ? K extends keyof U ? U[K] : never : never;
type Foo = TupleToUnion<A, 'a'>

CodePudding user response:

Yeah. I found one solution

type TupleToUnion<T, K> = T extends [infer R, ...infer Rest]
  ? K extends keyof R
    ? R[K] | TupleToUnion<Rest, K>
    : never
  : never;
  • Related