Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flow property is missing in mixed passed

I'm using a BroadcastChannel to pass data from one browser window to another. However, using Flow I get the following error: Flow: property `type` is missing in mixed [1].

This is my code:

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 });
  }
};

I also tried to define my own type as such:

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 });
  }
};

But then Flow gives me the following error: Flow: Cannot assign function to `channel.onmessage` because `MessageType` [1] is incompatible with mixed [2] in property `data` of the first argument.

I figured out that the argument, passed by the message handler is declared like this:

declare class MessageEvent extends Event {
  data: mixed;
  origin: string;
  lastEventId: string;
  source: WindowProxy;
}

So, if data is declared to be of type mixed but I need it to be a custom type, how would I do that?

like image 721
lenny.myr Avatar asked Jan 09 '19 13:01

lenny.myr


People also ask

What is mixed type flow?

Definition of mixed-flow : combining or utilizing in succession two or more different types of flow (as axial and radial) —used especially of turbines and pumps.

What are mixed types?

Until now, we have learned that two parts or clauses in conditional sentences have the same times. In some cases, unreal conditional sentences are mixed. Namely, the time in the If-Clause is not the same as the time in Main Cause. When it is so, these sentences or clauses are called mixed types or mixed conditionals.


1 Answers

Values of type mixed can be absolutely anything, including undefined, null or objects without a prototype.

You need to explicitly check that the actual type of data has a type field before being able to access it:

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 });
    }
  }
};
like image 124
Peter Hall Avatar answered Sep 28 '22 06:09

Peter Hall