2 种在 TypeScript 中合并对象的方法
这篇快速文章向您展示了在 TypeScript 中合并 2 个或更多对象的 2 种不同方法。事不宜迟,让我们动手吧。
使用扩展运算符
您需要记住一些重要的事情:
- 通过使用扩展语法 (…),将自动推断合并对象的类型。如果您打算在最终对象中添加/删除属性,TypeScript 会对您大喊大叫(如果您只想更新属性的值,这很好)。
- 对象的顺序很重要。如果对象有重复的键,则只保留与最后一个对象的键对应的值
例子:
const objectOne = {
name: 'Product One',
price: 100,
description: 'This is product one',
};
const objectTwo = {
weight: 100,
color: 'red',
};
const objectThree = {
name: 'Product Three',
descriptioN: 'KindaCode.com',
color: 'blue',
};
// merging objectOne and objectTwo
const a = { ...objectOne, ...objectTwo };
console.log(a);
// merging three objects
// the last object will override the previous objects
const b = { ...objectOne, ...objectTwo, ...objectThree };
console.log(b);
输出:
// console.log(a);
{
name: 'Product One',
price: 100,
description: 'This is product one',
weight: 100,
color: 'red'
}
// console.log(b);
{
name: 'Product Three',
price: 100,
description: 'This is product one',
weight: 100,
color: 'blue',
descriptioN: 'KindaCode.com'
}
如果您将鼠标悬停在其中一个结果上,您会看到它的类型:
使用 Object.assign() 方法
这种方法与前一种方法几乎相同。
例子:
const objectOne = {
name: 'Product One',
price: 100,
description: 'This is product one',
};
const objectTwo = {
weight: 100,
color: 'red',
};
const objectThree = {
name: 'Product Three',
descriptioN: 'KindaCode.com',
color: 'blue',
};
// Merge objectOne and objectTwo by using Object.assign()
const resultOne = Object.assign({}, objectOne, objectTwo);
console.log(resultOne);
// Merge objectOne, objectTwo, and objectThree by using Object.assign()
const resultTwo = Object.assign({}, objectOne, objectTwo, objectThree);
console.log(resultTwo);
输出:
// console.log(resultOne);
{
name: 'Product One',
price: 100,
description: 'This is product one',
weight: 100,
color: 'red'
}
// console.log(resultTwo);
{
name: 'Product Three',
price: 100,
description: 'This is product one',
weight: 100,
color: 'blue',
descriptioN: 'KindaCode.com'
}
TypeScript 很聪明,能够推断出结果的类型,如下面的截图所示:
这里有一个小的区别。组合对象的类型是使用 & 定义的交集类型 & 。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。