[英]How to implement a factory method in typescript?
My code: 我的代码:
class Model {}
class Loader {
static load<M extends Model>(ModelClass: typeof Model): M {
return new ModelClass();
}
}
Error message: Type 'Model' is not assignable to type 'M'.
错误消息:
Type 'Model' is not assignable to type 'M'.
Link to Playground: goo.gl/qrSsoX 链接到游乐场:goo.gl/qrSsoX
We should say that load
take a class as argument not an instance. 我们应该说,
load
将类作为参数而不是实例。
export interface Type<T> extends Function { new (...args: any[]): T; }
class Model {}
class Loader {
static load<M extends Model>(ModelClass: Type<M>): M {
return new ModelClass();
}
}
for more information take a look at this answer 有关更多信息,请查看此答案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.