typescript - 如何推断实现接口(interface)的类类型

标签 typescript

给定一个接口(interface):

interface IAnInterface {

}

如何引用和指向实现该接口(interface)的类类型?

含义,给定一个类:

class AClassThatImplmentsAnInterface implements IAnInterface {

}

如何引用属于类类型的类型?如果它只是类,我们可以使用 typeof :

typeof AClassThatImplementsAnInterface

但是在接口(interface)层,它指向所有实现该接口(interface)的类:

typeof IAnInterface

给出错误:

'IAnInterface' only refers to a type, but is being used as a value here. (2693)

我想做这样的事情:

type IClassTypeMapping = {
 [names in SomeLiteralStringUnion]: Class<IAnInterface>
}

当然Class在 TypeScript 中不存在。如何引用 Class<IAnInterface> 的等价物?在 TypeScript 中甚至可能吗?

最佳答案

我假设您正在尝试映射到类本身,而不是类的实例。所以基本上有的东西是可以构造的。我认为这种类型应该适合你:

type Class<I, Args extends any[] = any[]> = new(...args: Args) => I;

我们声明 Class<IAnInterface>可以用 new 调用关键字和一些参数,并将返回 IAnInterface对象(类实例)。

第二个参数Args允许您定义构造函数参数是什么。如果没有参数,它将是一个空数组。

declare const MyClass: Class<IAnInterface, []>;

const instance: IAnInterface = new MyClass();
declare const OtherClass: Class<IAnInterface, [number, string]>;

const otherInstance: IAnInterface = new OtherClass(0, "");

Playground Link

关于typescript - 如何推断实现接口(interface)的类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64750214/

相关文章:

javascript - groupBy 与 Lodash 模块

javascript - Angular获取特定文件夹内的所有文件名

javascript - 如何在 Typescript 中缩短这个条件?

javascript - 在 Angular 2 中绑定(bind) ngmodel 中的 json 值

javascript - Window 对象是否有获取/设置键的方法?

reactjs - React hook 中的 Object.is 相等性检查导致同一函数有多个版本

javascript - 为什么在将 Paho MQTT 函数从 Angular 1 迁移到 Angular 2 时收到 typescript 错误?

javascript - typescript 找不到名称窗口或文件

json - Angular 2 : How to preserve class methods on deserialization?

angular - super() 中的 typescript 依赖注入(inject)