【发布时间】:2019-07-09 01:46:19
【问题描述】:
我们有一个基础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);
【问题讨论】:
-
你不能让
doSomething()通用吗?FactStoreObject不能创建通用的StoreObject<S>实例...它只能创建StoreObject<Fact>实例。
标签: typescript typescript-typings typescript-generics