我有一个超类,它是许多子类(Customer, Product, ProductCategory…)的父类(Entity)。

我想在Typescript中动态克隆一个包含不同子对象的对象。

例如:拥有不同产品的客户拥有一个ProductCategory

var cust:Customer  = new Customer ();

cust.name = "someName";
cust.products.push(new Product(someId1));
cust.products.push(new Product(someId2));

为了克隆对象的整个树,我在实体中创建了一个函数

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时,将引发以下错误:错误TS2351:不能对缺少调用或构造签名的表达式使用'new'。

虽然脚本工作,但我想摆脱转译错误


当前回答

如果你已经有了目标对象,所以你不想重新创建它(就像更新一个数组一样),你必须复制属性。 如果这样做:

Object.keys(source).forEach((key) => {
    copy[key] = source[key]
})

赞美是应得的。(请看标题“版本2”)

其他回答

试试这个:

let copy = (JSON.parse(JSON.stringify(objectToCopy)));

这是一个很好的解决方案,直到您使用非常大的对象或对象具有不可序列化的属性。

为了保持类型安全,你可以在你想复制的类中使用一个copy函数:

getCopy(): YourClassName{
    return (JSON.parse(JSON.stringify(this)));
}

或以静态的方式:

static createCopy(objectToCopy: YourClassName): YourClassName{
    return (JSON.parse(JSON.stringify(objectToCopy)));
}

jQuery怎么样?!下面是深度克隆:

var clone = $.extend(true, {}, sourceObject);

你可以在扩展语法中使用解构赋值:

var obj = {id = 1, name = 'product1'};
var clonedObject = {...obj};

对于一个简单的克隆的hole对象的内容,我简单地stringify和解析实例:

let cloneObject = JSON.parse(JSON.stringify(objectToClone))

当我在objectToClone树中更改数据时,在cloneObject中没有更改。这就是我的要求。

希望能有所帮助

最后我这样做了:

public clone(): any {
  const result = new (<any>this.constructor);

  // some deserialization code I hade in place already...
  // which deep copies all serialized properties of the
  // object graph
  // result.deserialize(this)

  // you could use any of the usggestions in the other answers to
  // copy over all the desired fields / properties

  return result;
}

因为:

var cloneObj = new (<any>this.constructor());

@Fenton给出了运行时错误。

Typescript版本:2.4.2