Arrays 如何在TypeScript中组合两个不同类型的对象?

Arrays 如何在TypeScript中组合两个不同类型的对象?,arrays,typescript,object,Arrays,Typescript,Object,最初,我定义 a = {}; b:any; 经过一些处理,我得到 a = {p:"ram", f:"sita"}; b = {"gita","mita"}; 我试图合并这两个结果。我试过了 cart = []; cart.push(this.a); cart.push(this.b); console.log(this.cart); 并得到如下结果: {p: "ram", f: &quo

最初,我定义

a = {};
b:any;
经过一些处理,我得到

a = {p:"ram", f:"sita"};

b = {"gita","mita"};
我试图合并这两个结果。我试过了

cart = [];

cart.push(this.a);
cart.push(this.b);
console.log(this.cart);
并得到如下结果:

{p: "ram", f: "sita"}

{b: ["gita","mita"]}
我想要的结果是:

a ={p:"ram", f:"sita", b:"gita","mita"}

如何实现上述目标。

您发布的示例既不是有效的TypeScript,也不是JavaScript,但我认为您的意思是:

a      = { p: "1", f: "2" };
b      = [ "3", "5" ];
output = { p: "1", f: "2", b: [ "3", "5" ] };
在这种情况下,您不需要做任何特殊的事情:TypeScript完全理解
对象。assign
做什么:

interface AWithB {
    readonly a: { readonly p: string, readonly f: string };
    readonly b: readonly string[];
}

const a      = { p: "1", f: "2" };
const b      = [ "3", "5" ];
const output = Object.assign( {}, a, { b: b } );

function requiresAWithB( arg: AWithB ): void {
    console.log( arg );
}

requiresAWithB( output ); // <-- no error, because `output` matches `interface AWithB`.
接口AWithB{
只读a:{readonly p:string,readonly f:string};
只读b:只读字符串[];
}
常数a={p:“1”,f:“2”};
常数b=[“3”,“5”];
const output=Object.assign({},a,{b:b});
函数requiresWithB(参数:AWithB):无效{
控制台日志(arg);
}

带b(输出)的请求;//
{3”,“5”}
是无效的javascript,
{b:“3”,“5”}
也不是有效的javascript,那么你到底想要什么呢?我真的要避免使用any和
{/code>。我认为逐渐建立对象(通过随时间变化)是Typescript中的一种反模式。有更好的编写方法,只是在最后一步将所有属性合并到最后一个对象中。请不要改变变量。调试和键入都很困难。只是我的意见