【发布时间】:2019-06-04 06:33:13
【问题描述】:
我正在使用BroadcastChannel 将数据从一个浏览器窗口传递到另一个浏览器窗口。但是,使用 Flow 我得到以下错误:Flow: property `type` is missing in mixed [1].
这是我的代码:
const channel = new BroadcastChannel('background');
channel.onmessage = ({ data }) => {
if (data.type === 'OK') {
this.setState({ isLoading: false, success: true, error: false });
}
else if (data.type === 'ERROR') {
this.setState({ isLoading: false, success: false, error: true });
}
};
我也尝试过这样定义自己的类型:
type MessageType = {
type: String,
payload: String,
};
...
channel.onmessage = ({ data }: { data: MessageType }) => {
if (data.type === 'OK') {
this.setState({ isLoading: false });
}
if (data.type === 'ERROR') {
alert('ERROR!');
this.setState({ isLoading: false });
}
};
但是 Flow 给了我以下错误:Flow: Cannot assign function to `channel.onmessage` 因为 `MessageType` [1] 与第一个参数的属性 `data` 中的混合 [2] 不兼容。
我发现消息处理程序传递的参数是这样声明的:
declare class MessageEvent extends Event {
data: mixed;
origin: string;
lastEventId: string;
source: WindowProxy;
}
那么,如果数据被声明为混合类型,但我需要它是自定义类型,我该怎么做?
【问题讨论】:
标签: javascript flowtype