Typescript-合并具有不同接口的对象的重叠属性

时间:2020-03-06 12:38:13

标签: typescript

这可能是一个愚蠢的问题,但是我在以下接口方面有些挣扎。 我有两个对象:

interface Apple {
  color: 'red' | 'green'
}

interface Orange {
  variety: 'normal' | 'blood'
}

interface Banana {
  plantain: boolean
}


interface A {
  bananas: Banana[],
  oranges: Orange[],
  apples: Apple[],
  lookAtBanana: (banana: Banana) => Banana,
}

interface B {
  bananas: Banana[],
  apples: Apple[]
}

const mergeObjectsOption1 = (state: A, response: B)  => {
  for (const key in response) {
    state[key] = response[key] // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'B'.
  }
}

const mergeObjectsOption2 = (state: A, response: B)  => {
  for (const key in response) {
    const typedKey = key as keyof typeof response
    const value = response[typedKey];
    state[typedKey] = value; // this is as close as I get to the desired output,but still doesn't work
  }
}
}

那么,在Typescript中始终保留键入内容的同时进行这种简单操作的最佳方法是什么?我猜想是一个基于变量从联合中提取单个类型的运算符会有所帮助,但找不到任何:/

作为附加注释,类型A实际上是VueJS组件的this上下文。

此处的游乐场:https://stackblitz.com/edit/typescript-3xbbzd?file=index.ts

1 个答案:

答案 0 :(得分:0)

我将使用传播运算符来简化您的操作。

interface A {
...
}

interface B {
...
}

const mergeObjects = (a: A, b: B): (A & B) => {
    return {...a, ...b };
}

注意:对象在此处浅合并。另外,如果两个对象都具有某些公共属性,则后者(此处为 b )将覆盖前者的属性。