oliver
oliver

Reputation: 9475

Comparing enum values in Flow

I'm using flow to annotate types in my code.

type Bar = 'One' | 'Two';
function foo(b: Bar) : boolean {
  return b === 'Three';
}

Is there any way to teach flow to report a warning or an error for comparisons with non matching types (string in my case)?

here is the example for test

edit: so it seems not to be possible to do it with enums. but, since this is actually an error I encountered, I'd like to express this so that flow will help me flag such a situation.

Any ideas for that?

Upvotes: 6

Views: 755

Answers (2)

oliver
oliver

Reputation: 9475

this is another way I could think of:

type Bar = 'One' | 'Two';

function eq(a: Bar, b: Bar): boolean {
  return a === b;
}
function foo(b: Bar) : boolean {
  // compare b to 'Three'
  return eq(b, 'Three');
}

will result in

return eq(b, 'Three');
                  ^ string. This type is incompatible with the expected param type of 
function eq(a: Bar, b: Bar): boolean {
                       ^ string enum

to be found here

Upvotes: 0

Meligy
Meligy

Reputation: 36584

You can use the format (value: Type) . In your case that would be:

type Bar = 'One' | 'Two';
function foo(b: Bar) : boolean {
  return b === ("Three": Bar);
}

Which will show the error.

Updated example.

Upvotes: 3

Related Questions