Can I safely use Switch over FlowType (String Enums) connection types?

In the following example, since I use message type matching with the switch statement, I would like the thread to recognize my incorrect case with "ENUM_TYPO". This is currently not the case.

type Message = 'BROADCAST_MESSAGE' | 'PRIVATE_MESSAGE'; const message: Message = 'BROADCAST_MESSAGE'; switch (message) { case 'ENUM_TYPO': // Do Broadcast break; default: break; } 
+5
source share
1 answer

Starting with v0.32.0, Flow does not complain about unreachable code, unless 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 {}; } 

There will be no errors in this code at this time. The thread actually notes that x === 123 will never be true. Inside the if block, the thread will refine the type x to an empty type, since it does not believe that this code will ever be reached. This is why it does not complain about the return x .

One member of the Flow team is almost complete with the addition of availability analysis for the flow. As soon as this improvement lands (I assume v0.34.0?), Flow will complain when it sees a condition that, in its opinion, will always fail. This will help you in your example, since the cases of switch statements are basically strict equality checks.

+4
source

All Articles