从元组中的属性中提取值

sun*_*day 6 typescript

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

TupleToUnion<A, 'a'> // expected to be `1 | 'x'`
Run Code Online (Sandbox Code Playgroud)

我该如何定义TupleToUnion

Iai*_*ton 7

要获取您的类型,无需使用泛型,您可以使用此索引访问类型

type B = A[number]['a']
Run Code Online (Sandbox Code Playgroud)

以下泛型类型应该能够模拟上述内容。T首先推断(as )中所有对象的联合类型U,然后在K断言它有效并扩展可用键后对该联合进行索引

操场

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'>
Run Code Online (Sandbox Code Playgroud)