【问题标题】:Flow property is missing in mixed passed混合传递中缺少流属性
【发布时间】: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


    【解决方案1】:

    mixed 类型的值绝对可以是任何值,包括undefinednull 或没有prototype 的对象。

    您需要明确检查data 的实际类型是否具有type 字段,然后才能访问它:

    channel.onmessage = ({ data }) => {
      // 1. Make sure it's not null
      // 2. Make sure it's an object. This is only so that we can...
      // 3. ...call hasOwnProperty to make sure it has a 'type' field
      if(data != null && typeof data === 'object' && data.hasOwnProperty('type')) {
        // Inside this condition, Flow knows that the 'type' field exists
        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 });
        }
      }
    };
    

    【讨论】:

    • 甜蜜!谢谢:)
    • 这个有什么捷径吗?
    • 这里可以简化为if (data && data.type) {data.type === 'OK' ? this.setState(some_state) : this.setState(other_state);}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2018-08-27
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多