TypeScript - 基于保存对构造函数的引用的变量定义类型

问题描述 投票:0回答:1

是否有可能获得一个保存对构造函数/类的引用的变量类型?

我正在做:

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)。

typescript metaclass typeof type-definition
1个回答
1
投票
type MyConstructor = new (...args: any[]) => MyComponent

let x: MyConstructor
let y = new x()
© www.soinside.com 2019 - 2024. All rights reserved.