Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to safely use Switch over FlowType union types (String Enums)?

Tags:

flowtype

In the following example, since I'm using matching over type of Message using the switch statement, I would like flow to recognise my incorrect case of 'ENUM_TYPO'. It currently doesn't.

type Message = 'BROADCAST_MESSAGE' | 'PRIVATE_MESSAGE';

const message: Message = 'BROADCAST_MESSAGE';

switch (message) {
  case 'ENUM_TYPO':
    // Do Broadcast
    break;
  default:
    break;
}
like image 497
Bahman Avatar asked Sep 21 '16 11:09

Bahman


1 Answers

As of v0.32.0, Flow does not complain about unreachable code, unless it's something like

// @flow
function foo() {
  throw new Error();
  return 123; // This will error
}. 

However, consider the following code

// @flow
function foo(x: string): Object {
  if (x === 123) {
    return x;
  }
  return {};
}

Will currently will not error on this code. Flow does in fact notice that x === 123 will never be true. Inside the if block, Flow will refine the type of x to the empty type, since it doesn't believe that this code will ever be reached. That is why it doesn't complain about the return x statement.

One of the members of the Flow team is almost done with adding reachability analysis to Flow. Once this improvement lands (I'm guessing v0.34.0?), Flow will complain when it sees a conditional that it thinks will always fail. This will help you with your example, since switch statement cases are basically strict equality checks.

like image 77
Gabe Levi Avatar answered Oct 18 '22 07:10

Gabe Levi