I have a super class that is the parent ( Entity
) for many subclass ( Customer
, Product
, ProductCategory
…)
我正在寻找动态克隆一个包含 Typescript 中不同子对象的对象。
例如: Customer
有不同的 Product
谁有 ProductCategory
var cust:Customer = new Customer ();
cust.name = "someName";
cust.products.push(new Product(someId1));
cust.products.push(new Product(someId2));
为了克隆整个对象树,我在 Entity
中创建了一个函数
public clone():any {
var cloneObj = new this.constructor();
for (var attribut in this) {
if(typeof this[attribut] === "object"){
cloneObj[attribut] = this.clone();
} else {
cloneObj[attribut] = this[attribut];
}
}
return cloneObj;
}
new
转译为 javascript 时出现以下错误: error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.
虽然脚本有效, 但我想摆脱编译错误
原文由 David Laberge 发布,翻译遵循 CC BY-SA 4.0 许可协议
解决具体问题
您可以使用类型断言告诉编译器您更了解:
克隆
截至 2022 年,有一项提议允许
structuredClone
深度复制许多类型。你可以在什么样的东西上使用 它有一些限制。
请记住,有时最好编写自己的映射 - 而不是完全动态的。但是,您可以使用一些“克隆”技巧来获得不同的效果。
我将在所有后续示例中使用以下代码:
选项 1:传播
属性: 是的
方法:没有
深拷贝:否
选项 2:Object.assign
属性: 是的
方法:没有
深拷贝:否
选项 3:Object.create
属性: 继承
方法: 继承
Deep Copy: Shallow Inherited (深度更改影响原始和克隆)
选项 4:深度复制功能
属性: 是的
方法:没有
深拷贝: 是