对于TypeScript 1.7中的Polymorphic,我在这里发现,我们可以在类中定义一个返回类型为的方法this,并自动地,任何扩展该类并继承方法的类,将其返回类型设置为各自的this类型.像这样:
class Model {
save():this { // return type: Model
// save the current instance and return it
}
}
class SomeModel extends Model {
// inherits the save() method - return type: SomeModel
}
Run Code Online (Sandbox Code Playgroud)
但是,我所追求的是拥有一个static带有返回类型的继承方法,引用类本身.最好用代码描述:
class Model {
static getAll():Model[] {
// return all recorded instances of Model as an array
}
save():this {
// save the current instance and return it
}
}
class SomeModel extends Model …Run Code Online (Sandbox Code Playgroud) 我有两个类:模型和用户.用户扩展了模型.
export Model {
id: number;
static fromData<T>(data: any): T {
return Object.assign(new Model(), data);
}
}
export User extends Model {
name: string;
sayHi(): string {
return 'Hi, ' + this.name;
}
}
Run Code Online (Sandbox Code Playgroud)
我想用它的方式如下:
const currentUser = User.fromData(dataFromServer);
const message = currentUser.sayHi();
Run Code Online (Sandbox Code Playgroud)
方法hi()不起作用,因为我已经创建了Model类的实例.
如何使用TypeScript泛型使用基类静态方法获取派生类的实例?
我正在计划一些共同的不同实体.
我看到了这个答案,但我不知道在我的情况下如何将参数传递给静态方法.