如何在typescript中的基类中创建相同类型的实例

时间:2016-09-11 17:43:24

标签: inheritance typescript types

如果B扩展A,A可以定义一个创建新B的方法吗?

progress_attachments

1 个答案:

答案 0 :(得分:5)

你走了:

type SetConstructor<T extends SetA> = {
    new (items:any[]): T;
}

class SetA {
   constructor(public items:any[]) {}

   createNew(items): this {
      return new (this.constructor as SetConstructor<this>)(items);
   }

   clone(){
      return this.createNew(this.items);
   }
}

code in playground

createNew方法的返回类型为this Polymorphic this types