【问题标题】:How to check for undefined before assigning to variable如何在分配给变量之前检查未定义
【发布时间】:2022-07-15 15:35:14
【问题描述】:

我正在使用 find 方法来提取 ID(字符串),但这会返回一个未定义的,因为它不存在。

const additionalLinePhoneNumber = products.find(product => product.name === 'segundaLinea').id;

产品有以下:

(2) [ProductInventoryList, ProductInventoryList]
0: ProductInventoryList {_id: "12345", _name: "lineaFija", _productInventoryCharacteristics: ProductInventoryCharacteristics}
1: ProductInventoryList {_id: "12345", _name: "primeraLinea", _productInventoryCharacteristics: ProductInventoryCharacteristics}
length: 2

所以“segundaLinea”没有返回,所以查找给了我以下错误:

ERROR 错误:未捕获(承诺中):TypeError:无法读取未定义的属性“id” 类型错误:无法读取未定义的属性“id”

我试过这样做但没有用:

const additionalLinePhoneNumber = products.find(product => product.name === 'segundaLinea').id ? undefined : '';

我错过了什么?

试试下面的遮阳篷:

【问题讨论】:

    标签: typescript angular5


    【解决方案1】:

    你可以像这样使用optional chaining

    const additionalLinePhoneNumber = products.find(product => product.name === 'segundaLinea')?.id;
    

    编辑:

    对于 Typescript,通过 version 3.7 添加了对可选链接的支持。如果您无法更新您的版本,则必须在多行中进行:

    const segundaLinea = products.find(product => product.name === 'segundaLinea');
    const additionalLinePhoneNumber = segundaLinea ? segundaLinea.id : "";
    

    如果你必须多次这样做,你可能应该编写一个辅助函数。

    【讨论】:

    • 我也试过了,没用:(
    • @MONZTAAA 您应该尝试 Arkellys 提供的示例,因为它确实有效。
    • @MONZTAAA 对于您在问题中提供的错误,我看不出它是如何工作的。您确定错误来自这一行吗?
    • @MONZTAAA 你使用的是什么版本的 Typescript?如果你有旧版本,你应该尝试更新它。
    • 2.6.1 更新不了,不是我自己的项目。
    【解决方案2】:

    如果你不想更新,只需添加if条件

    const segundaLinea = products.find(product => product.name === 'segundaLinea');
    if ( segundaLinea && segundaLinea.id ) {
        const additionalLinePhoneNumber = segundaLinea.id;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-16
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多