1

Is there a way to refine a union of tuples correctly in flow? I see examples for object types in docs but looks like it has a difference for arrays and I don't see any clue for that case. I have this simple code:

/* @flow */

type A = ['a', string, string];
type B = ['b', number];

function process(param: A | B) {
  if (param[0] === 'a') {
    /*
     ERROR! Cannot get `param[2]` because `B` [1] only has 2 elements, 
     so index 2 is out of bounds. [invalid-tuple-index] 
    */
    console.log(param[2])
  } else {
    console.log(param[1])
  }
}

Flow Playground

But in typescript it distinguishes types correctly

type A = ['a', string, string];
type B = ['b', number];

function process(param: A | B) {
  if (param[0] === 'a') {
    console.log(param[2]) // Works! param: A
  } else {
    console.log(param[1]) // param: B
  }
}

Thanks!

Max Sinev
  • 5,884
  • 2
  • 25
  • 35
  • It's not supported. There's an open PR https://github.com/facebook/flow/pull/5048 Length based refinement is already implemented though: param[0] === 'a' -> param.length === 3 – Roman Pominov Jun 15 '22 at 16:30

0 Answers0