问题描述
// @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'
}
}
}
}
其他选择是使用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'
}
}
}
}