我想知道最好的方法,假设我有两个对象
var objectA = {
propertyA: 1,
propertyB: 2
...
propertyM: 13
}
var objectB = {
propertyN: 14,
propertyO: 15
...
propertyZ: 26
}
如果objectC是由
创建的var objectC = Object.assign(objectA, objectB);
如何声明/描述 objectC,以便编译器/IDE 知道它具有 objectA 和 objectB 的属性?
我想找到一种不需要为 objectA 和 objectB 定义接口(interface)的方法。我不想为同一个属性写两次声明和定义/评估。如果我在一个对象上有太多属性,这种冗余就很重要。
(有没有可以提取现有对象的接口(interface)/类型的算子?)
这可能吗?
最佳答案
看起来应该可以解决这个问题:
var objectA = {
propertyA: 1,
propertyB: 2,
.
. // more properties here
.
propertyM: 13
};
var objectB = {
propertyN: 14,
propertyO: 15,
.
. // more properties here
.
propertyZ: 26
};
var objectC = {...objectA, ...objectB}; // this is the answer
var a = objectC.propertyA;
var n = objectC.propertyN;
基于这篇文章:https://blog.mariusschulz.com/2016/12/23/typescript-2-1-object-rest-and-spread
此外,分解中变量的顺序很重要。 请考虑以下事项:
var objectA = {
propertyA: 1,
propertyB: 2, // same property exists in objectB
propertyC: 3
};
var objectB = {
propertyX: 'a',
propertyB: 'b', // same property exists in objectA
propertyZ: 'c'
};
// objectB will override existing properties, with the same name,
// from the decomposition of objectA
var objectC = {...objectA, ...objectB};
// result: 'b'
console.log(objectC.propertyB);
// objectA will override existing properties, with the same name,
// from the decomposition of objectB
var objectD = {...objectB, ...objectA};
// result: '2'
console.log(objectD.propertyB);
关于typescript - 如何在 typescript 中组合对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37042602/