typescript - 如何在 typescript 中组合对象属性?

标签 typescript

我想知道最好的方法,假设我有两个对象

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/

相关文章:

typescript - 根据子尺寸设置父尺寸的高度和宽度

typescript - 如何访问 Angular2 指令上的组件?

javascript - 如何将函数中的变量使用到同一类的其他 block 中

angular - 数据表显示使用 Angular 的表中没有可用数据

javascript - 为什么我在 TypeScript 中收到错误 cannot redeclare block-scoped variable 'name'?

Angular 8 : How to do calculation on observable object's two properties and need to save on another property

javascript - 如何用时刻获取给定年份的最后一天?

javascript - Angular 4.3.3 HttpClient : How get value from the header of a response?

javascript - 如何从 for 循环返回解析 Promise Like 对象

typescript - 如何检查discord.js 中交互的权限