是否有可能获得一个保存对构造函数/类的引用的变量类型?
我正在做:
const componentUnderTest = MyComponent;
type TComponentUnderTest = MyComponent;
我试图通过尝试"提取"来删除重复的MyComponent
。来自const componentUnderTest
的类型:
const componentUnderTest = MyComponent;
type TComponentUnderTest = typeof componentUnderTest; // note my attempt here
但是我收到了错误。
但是由于相关的构造有效:
const componentUnderTest: MyComponent = null;
type TComponentUnderTest = typeof componentUnderTest; // typeof works here
因此,我的Java本能暗示它应该是这样的:
type TComponentUnderTest = Type<typeof componentUnderTest>;
或
type TComponentUnderTest = Constructor<typeof componentUnderTest>;
或
type TComponentUnderTest = Class<typeof componentUnderTest>;
但是我不确定TypeScript中是否存在这样的通用元类类型...
有可能表达这样的事情吗?
这类似于Declaring type based on variable,除了我想引用构造函数/ class / type(const componentUnderTest = MyComponent
)。
答案 0 :(得分:1)
type MyConstructor = new (...args: any[]) => MyComponent
let x: MyConstructor
let y = new x()