如何解决通过类的联合来分配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>'.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。