Typescript,合并元组元素的对象类型

时间:2020-10-29 13:02:15

标签: typescript

是否可以采用不同对象的元组,并获得所有这些对象的组合类型?例如,如果我有一个这样的元组:

const t = tuple({current: 1}, {old: 2}, {new: 3}); //this should be interpreted as [{current: number;}, {old: number;}, {new: number;}]

然后将这些对象合并为一个对象:

let newob = {};
for(let ob of t) {
  Object.assign(newob, ob);
}

我能以某种方式使打字稿将此新对象视为

typeof t[0] & typeof t[1] & typeof t[2]

在这种情况下应该是

{current: number; old: number; new: number;}

没有手动输入所有内容?

我希望它可以与任何元组和元组内的任何对象一起使用

1 个答案:

答案 0 :(得分:1)

您可以使用对约束类型为any[]的约束的通用类型参数来捕获元组类型的参数。您可以使用here中描述的UnionToIntersection将所有元组项目类型合并为单个交集类型

type UnionToIntersection<U> = 
  (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never
function tuple<T extends any[]>(...t: T) {
  let newob = {} as UnionToIntersection<T[number]>;
  for (let ob of t) {
    Object.assign(newob, ob);
  }
  return newob;
}

Playground Link