繁体   English   中英

如何推断实现接口的 class 类型

[英]How to inference class type that implements an interface

给定一个接口:

interface IAnInterface {

}

如何引用并指向实现该接口的 class 类型?

含义,给定一个 class:

class AClassThatImplmentsAnInterface implements IAnInterface {

}

如何引用 class 类型的类型? 如果只是类,我们可以使用typeof

typeof AClassThatImplementsAnInterface

但在接口级别,它指向实现接口的所有类:

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, "");

游乐场链接

(仅适用于 Angular)

Angular 有一个内置 class:类型

您可以在相关问题中阅读更多内容

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM