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

问题描述

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

我一直在尝试做类似的事情。但是流程会产生错误Cannot assign 'class { ... }' to 'this.someError' because class '<<anonymous class>>' [1] is incompatible with 'Error'。对于我来说,将类变量写为:

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

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

解决方法

这是因为: Error代表类Error的实例,而不是类本身/构造函数。要获取构造函数类型,可以使用typeof运算符:

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

Try


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

鉴于类型T代表类C的实例,类型Class<T>是类C的类型

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

Try