[英]Flowtype error. Object type is incompatible with string
I wrote a small Javascript class that has an argument which accepts either a string or an object. 我编写了一个小的Javascript类,该类具有一个接受字符串或对象的参数。 However, I get this error:
但是,我收到此错误:
Error: utils/HttpError.js:8
8: message:string | ErrorObj
^^^^^^^^ object type. This type is incompatible with
512: message: string;
^^^^^^ string. See lib: /private/tmp/flow/flowlib_33322c59/core.js:512
I've tried not using the type alias, and simplifying the ErrorObj to just {}
, but I've had no luck. 我试过不使用类型别名,而是将ErrorObj简化为
{}
,但是我没有运气。 Is this a bug, or am I missing something? 这是一个错误,还是我缺少什么? I'm using flow-bin ^0.51.0.
我正在使用流箱^ 0.51.0。 My class is below.
我的课在下面。
//@flow
"use strict";
type ErrorObj = {[key:string]:Array<string>}
class HttpError extends Error {
status:number
message:string | ErrorObj
constructor(status:number, message: string | ErrorObj){
super();
this.status = status;
this.message = message;
}
toString():string{
return `status: ${this.status} message: ${JSON.stringify(this.message)}`;
}
}
module.exports = HttpError;
The internal definition of Error
has the message
member variable typed as simply a string. Error
的内部定义将message
成员变量键入为简单的字符串。 Even after subclassing, the base class ( Error
) still might interact with this.message
in some way. 即使在子类化之后,基类(
Error
)仍可能以某种方式与this.message
进行交互。 If you were able to redefine it to be anything other than a string, and it attempted to call length
or concat
or some other member of the String
class, it would fail. 如果您能够将其重新定义为字符串以外的任何其他字符,并且它尝试调用
length
或concat
或String
类的其他成员,则它将失败。 Therefore you cannot override member types of subclasses. 因此,您不能覆盖子类的成员类型。
You could instead try something like: 您可以改用类似的方法:
type ErrorObj = {[key:string]:Array<string>}
class HttpError extends Error {
status:number
_customMessage:string | ErrorObj
constructor(status:number, message: string | ErrorObj){
super(typeof message === 'string' ? message : null);
this.status = status;
this._customMessage = message;
}
toString():string{
return `status: ${this.status} message: ${JSON.stringify(this._customMessage)}`;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.