Saad
Saad

Reputation: 53839

Flow complaining about undefined even after type refinement

You can view the code on flow.org/try, or you can look at it here:

/* @flow */

type Thing = {
  arr?: Array<number>
}

const thing: Thing = {
  arr: [10, 20, 30]
}

function getSubArray(thing: Thing, index: number) {
  if (!thing.arr) return []

  return [
    ...thing.arr.slice(0, index),
    ...thing.arr.slice(index + 1)
  ]
}

const newArr = getSubArray(thing, 1)

I thought that doing if (!thing.arr) return [], would act as a "type refinement" and flow would understand that thing.arr was not undefined after that point. However, it is giving me an error saying

16:     ...thing.arr.slice(index + 1)           
           ^ call of method `slice`. Method cannot be called on possibly undefined value
16:     ...thing.arr.slice(index + 1)
           ^ undefined

Any help would be appreciated!

Upvotes: 1

Views: 207

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220994

The first call to arr.slice "could" mutate thing.arr to become undefined, making the second call to slice an error. Flow protects you from that possibility by invalidating the refinement.

You can store thing.arr in a const and use that instead (in all three locations) to avoid the potential bug.

Upvotes: 1

Related Questions