网站搜索

typescript - 如何获取元组类型元素的键的交集?


type Tuple=[{a:string,x:string,z:string},{b:string,x:string,z:string}]
type IntersectionOfTupleElementKeys<T>=...
type MyType = IntersectionOfTupleElementKeys<Tuple> // = ('a'|'x'|'z')&('b'|'x'|'z')='x'|'z'

我有一个元组类型,其每个元素类型都有共同的字段(例如类型 Tuple 的 x 和 z)。如何获取这些共同字段的交集('x'|'z')?

答案#1

你可以查询元组项类型的键:

type IntersectionOfTupleElementKeys<T extends readonly any[]> = keyof T[number];

type MyType = IntersectionOfTupleElementKeys<Tuple> // 'x'|'z'

操场


我们通过使用 T[number] 获取所有元组项类型的联合类型,然后将 keyof 应用于联合类型会产生它们键的交集。