gpt4 book ai didi

带有扩展运算符的 Typescript 构造函数

转载 作者:行者123 更新时间:2023-12-04 11:56:00 25 4
gpt4 key购买 nike

如果与扩展运算符一起使用,则需要将属性分配给从接口(interface)定义的唯一属性。

我期待使用带有扩展运算符的 typescript 构造函数的解决方案。

例如。

export interface IBrand {
id: string;
name: string;
}

export class Brand implements IBrand {
id: string;
name: string;

constructor(data: IBrand) {
this.id = data.id;
this.name = data.name;
}
}

这是一种选择,所以当我这样称呼这个类时,不知道有多少成员,但我只有 id, name到最终对象。
new Brand({...data })

案例:但是当我有 25 个以上的 key 时 data
export interface IBrand {
id: string;
name: string;
}

export class Brand implements IBrand {
id: string;
name: string;

constructor(data: Partial<IBrand>) {
Object.assign(this, data);
}
}

我希望不要再次编写所有属性的构造函数。不管它有 25 个,它只是分配现有的属性将被分配。如果数据有 section, genre或任何其他属性,它将被忽略。

我的第二个片段不起作用。

最佳答案

这不使用扩展运算符,但您可以使用 this answer 中的方法

constructor(data: IBrand) {
for (let key in data) {
this[key] = data[key];
}
}

然后实例化...
new Brand(data);

关于带有扩展运算符的 Typescript 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56040302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com