Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Inheritance 如何在typescript中的基类中创建相同类型的实例_Inheritance_Typescript_Types - Fatal编程技术网

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

Inheritance 如何在typescript中的基类中创建相同类型的实例,inheritance,typescript,types,Inheritance,Typescript,Types,如果B扩展了A,A可以定义一个方法来创建一个新的B吗 class SetA { constructor(public items:any[]) { } createNew(items){ return new *typeof this*(items); //<-- insert actually working magic here } clone(){ return this.createNew(this.items); } }

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

class SetA {
   constructor(public items:any[]) {
   }
   createNew(items){
      return new *typeof this*(items); //<-- insert actually working magic here
   }
   clone(){
      return this.createNew(this.items);
   }
}
class SetB extends SetA { }

var x = new SetB([1,2,3]);
x.clone(); //<-- returns a new SetB
类SetA{
建造商(公共项目:任何[]){
}
创建新的(项目){
返回此*(项目)的新*类型;//给您:

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);
   }
}
type SetConstructor={
新(项目:任何[]):T;
}
类刚毛{
构造函数(公共项:any[]){}
createNew(项目):此{
返回新的(this.constructor作为SetConstructor)(项目);
}
克隆(){
返回this.createNew(this.items);
}
}
()

createNew
方法的返回类型是
this
,它是。

给你:

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);
   }
}
type SetConstructor={
新(项目:任何[]):T;
}
类刚毛{
构造函数(公共项:any[]){}
createNew(项目):此{
返回新的(this.constructor作为SetConstructor)(项目);
}
克隆(){
返回this.createNew(this.items);
}
}
()


createNew
方法的返回类型是
this
,它是。

太好了!太好了!太好了!