typescript - 将 typeof 分布在类的联合上
问题描述
考虑这个例子:
class A {}
class B {}
type AB = A | B
// type ABT = typeof AB // this does not work, error "AB is used as a value here"
type ABT = typeof A | typeof B
是否可以typeof
在不重复成员的情况下通过工会分配?
解决方案
如果你只是想要一个构造函数类型,你可以使用这个:
type Constructor<T> = new (...args: unknown[]) => T
type ABT = Constructor<AB> // new (...args: unknown[]) => AB
您可以使用instanceof
它,它还允许子类:
const something = (Class: ABT, object: unknown) => {
if (object instanceof Class) {
object // type AB
}
}
class C extends A {}
something(C, {})
但是,如果该类具有静态成员,则这与typeof
:
class D {
static x = 0
}
declare const typeofD: typeof D
declare const constructorD: Constructor<D>
new typeofD()
new constructorD()
typeofD.x
constructorD.x // Property 'x' does not exist on type 'Constructor<D>'.
推荐阅读
- postgresql - 自带加密 - Postgresql 10 - 多租户数据库
- c - 如何在C中按值“删除”数组中的每个元素
- vim - 重新附加的 tmux 会话未导入 ~/.bashrc
- objective-c - 创建视图时获取 EXC_BAD_ACCESS / KERN_INVALID_ADDRESS
- netlogo - 在 Netlogo 6.0.4 中创建接收器补丁
- android - 如何在 Ubuntu 中为 android 构建开放 SSL
- c++ - 使用统一初始化 {} 初始化二维向量
- windows - 病原体只加载一些插件
- swift - Xcode 9 项目不再使用 Xcode 10.1 编译,抱怨初始化程序。如何进行故障排除?
- javascript - 如何在反应组件中为内部函数声明一个变量?