即使在类型细化之后,流仍然抱怨未定义

时间:2017-10-04 08:38:26

标签: javascript flowtype

您可以在flow.org/try上查看代码,也可以在此处查看:

/* @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)

我认为执行if (!thing.arr) return []会充当“类型细化”,并且流程会理解thing.arr在此之后不是undefined。但是,它给我一个错误说

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

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

第一次致电arr.slice&#34;可以&#34;将thing.arr变为undefined,使第二次调用slice出错。 Flow通过使细化无效来保护您免受这种可能性。

您可以将thing.arr存储在const中,然后使用它(在所有三个位置)以避免潜在的错误。

相关问题