代码之家  ›  专栏  ›  技术社区  ›  user1283776

如何去掉数组函数中的“object is possible undefined”?

  •  0
  • user1283776  · 技术社区  · 4 年前

    在下面的代码中,我得到一个ts错误 output 可能未定义。我如何才能摆脱那个错误,继续我的编码?我本以为,由于我使用 && 访问上的属性之前 undefined 我不会得到一个类型错误。

    const outputs = stack.Outputs;
    if (!outputs) {
      throw new Error(`Unable to get stack output. Stack ${stackName} has no outputs.`)
    }
    
    const output = outputs.find(output => output && output.OutputKey === outputKey)
    

    enter image description here

    1 回复  |  直到 4 年前
        1
  •  0
  •   Pedro Barreto    4 年前

    设置一个条件,使其仅在find方法未定义的情况下执行。

    示例:

    if(output) {
    outputs.find(output => output && output.OutputKey === outputKey)
    }
    
    推荐文章