typescript - Typeof typescript 类不能分配给扩展它的类
问题描述
我们有一个基StoreObject
类,它为保存到数据库的对象提供转换/清理等通用方法。我希望能够使用泛型从这些方法中指定更严格的返回类型。typeof StoreObject
但是,在将 与进行比较时,我的尝试会导致错误typeof AClassThatExtendsStoreObject
,这是我们在各种实用程序函数中所做的检查。你能指出我在下面做错的方向吗?
class StoreObject<S> {
toStoreObject(s: S): S {
// Perform some sanitisation etc.
return s;
}
}
interface Fact {
id: string;
fact: string;
}
// A concrete implementation of StoreUnit where we attempt to define the actual model of the object being stored
class FactStoreObject extends StoreObject<Fact> {}
// We've got some general utils that interact objects using these classes
// These typicallay take a concrete implementation of StoreUnit to be used as a parser/processer
function doSomething(StoreObjectClass: typeof StoreObject) {
// Typically:
// const parsedObject = new StoreObjectClass(someObject).toStoreObject()
// persistToDb(parsedObject)
}
// This errors with "Type 'S' is not assignable to type 'Fact'"
doSomething(FactStoreObject);
解决方案
错误是由于这一行:
const parsedObject = new StoreObjectClass(someObject)
首先,您需要可构造的接口:
export interface IConstructable<T> {
new (): T;
}
其次,您需要将类型的参数包含到您的工厂方法中:
function doSomething<T>( t: IConstructable<T> ) {
const parsedObject = ( new t() ).toStoreObject();
// persistToDb(parsedObject);
}
推荐阅读
- c++ - C++ 中 gRPC 中的自定义异常处理
- java - 在非请求范围进程中访问请求范围的 bean
- android - Android 和 Kotlin DeteKt:自定义规则未运行
- python - 将线程名称作为全局变量传递给函数
- java - 用于以版本格式提取数字的正则表达式
- excel - 如何使用 End(xlUp) 清除从单元格 A4 开始的所有行
- c# - 如何在 c# 中使用预定义的指数和模数加密字符串?
- angular - Angular 10:使用 MatTable Paginator 时出现多个错误无法读取未定义的属性“长度”
- c# - 时间:2019-01-10 标签:c#deserializexml与动态标签名
- r - for-loop 或在多个子图上应用函数