首页 > 解决方案 > 将 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在不重复成员的情况下通过工会分配?

标签: typescriptclassconstructorunion

解决方案


如果你只是想要一个构造函数类型,你可以使用这个:

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>'.

游乐场链接


推荐阅读