给定一个接口(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, "");
关于typescript - 如何推断实现接口(interface)的类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64750214/