【问题标题】:How to fix flow type length error in array?如何修复数组中的流类型长度错误?
【发布时间】:2018-09-11 13:45:46
【问题描述】:

下面说我的代码

//@flow
type something = (input:Array<{data:?number}|{data<Object>}>) => boolean

function some:something(own){
 if(!own[0].data.length)
  return false
}

我收到消息: 财产length, 无法访问可能为空值的属性 空或未定义

如何解决? 因为在函数中有些可以解析 1. 带有内部对象或可能不是对象的数组。 2. 内部对象和对象中的数组可以是对象数组或空/未定义数组的数据 3. 如果是这样,如何在流类型中声明长度

【问题讨论】:

  • 提供的示例甚至不接近有效的流语法,您将收到一长串错误。请确保示例的准确性并提供错误输出的副本。

标签: reactjs flowtype flow-typed


【解决方案1】:

flow 给您一个错误,因为您尝试访问 data 上的属性 length - 您声明可能未定义...因此您需要“指示”您检查过的 flow:

function some:something(own){
 if(own[0].data && !own[0].data.length) // if an data property exists AND is not an array
  return false
}

顺便说一句,如果您只是尝试检查 own[0].data 是否是一个数组,那就这样做:

if(Array.isArray(own[0].data)) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    相关资源
    最近更新 更多