Inheritance 如何在typescript中的基类中创建相同类型的实例
如果B扩展了A,A可以定义一个方法来创建一个新的B吗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); } }
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
,它是。太好了!太好了!太好了!