如何在 Flow 中定义一个 class 变量以扩展另一个类型?

How to define a class variable in Flow so that it extends another type?

// @flow
class Demo {
    SomeError: Error
  
    constructor() {
        this.SomeError = class extends Error {
            constructor(message: string) {
                super(message)
                this.name = 'SomeError'
            }
        }
    }
}

我一直在尝试做类似的事情。但是flow报错:Cannot assign 'class { ... }' to 'this.SomeError' because class '<<anonymous class>>' [1] is incompatible with 'Error'。我将 class 变量写为的临时且丑陋的解决方案:

// ...
ErrorClass: Object
// ...

我不明白为什么它接受 Object 作为类型而不接受 Error。这个问题有解决办法吗?

那是因为 : Error 表示 class Error 的实例,而不是 class itself/constructor 的实例。要获取构造函数类型,您可以使用 typeof 运算符:

class Demo {
    SomeError: typeof Error
  
    constructor() {
        this.SomeError = class extends Error {
            constructor(message: string) {
                super(message)
                this.name = 'SomeError'
            }
        }
    }
}

Try


其他选项是使用 Class 实用程序。

Given a type T representing instances of a class C, the type Class<T> is the type of the class C

class Demo {
    SomeError: Class<Error>
  
    constructor() {
        this.SomeError = class extends Error {
            constructor(message: string) {
                super(message)
                this.name = 'SomeError'
            }
        }
    }
}

Try