简体   繁体   中英

Combined Enum in Flow Type

I have an enum that is the combination of two other enums (all string literals) in flowtype .

Now I have a function f1 that just accepts part of the enum. Based on an if clause, I want to make sure to pass only correct arguments to this f1 .

If I use if to match on strings, it works. But as soon as I have a variable with the exact same string, it errors.

See code:

Link to Flow-Playground

Why does f3 error?

 /* @flow */ type Enum1 = 'a' | 'b'; type Enum2 = 'c'; type Enum3 = Enum1 | Enum2; const c = 'c'; // same problem if I use: // const c: Enum2 = 'c'; const f1 = (e1: Enum1) => console.log(e1); // this works const f2 = (e3: Enum3) => { if (e3 !== 'c') { f1(e3); } } // this breaks - why? const f3 = (e3: Enum3) => { if (e3 !== c) { f1(e3); } } // this works const f4 = (e3: Enum3) => { if (e3 !== c) { (e3 === 'c' ? '' : f1(e3)) } } 

Type refinements need to be done with literals. This might also be a conflict with refinement invalidations - the call to f1 could invalidate the refinement, through modifying the value of var c .

const f3 = (e3: Enum3) => {
  if (e3 !== 'c') {  // literal c, not var c
    f1(e3);
  }
}

In effect, you're doing that same thing in f4 , because you are comparing to literal c and only calling f1 if its equivalent to Enum1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM