首页 > 解决方案 > 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);

游乐场链接

标签: typescripttypescript-typingstypescript-generics

解决方案


错误是由于这一行:

const parsedObject = new StoreObjectClass(someObject)

首先,您需要可构造的接口:

export interface IConstructable<T> {
    new (): T;
}

其次,您需要将类型的参数包含到您的工厂方法中:

function doSomething<T>( t: IConstructable<T> ) {
  const parsedObject = ( new t() ).toStoreObject();
  // persistToDb(parsedObject);
}

推荐阅读