【问题标题】:Typescript - Object is possibly 'null'.ts(2531) after null check打字稿 - 空检查后对象可能是'null'.ts(2531)
【发布时间】:2021-08-09 14:16:09
【问题描述】:

在空检查后,我得到 Object is possible 'null'.ts(2531)。有人可以帮我吗?我是不是做错了什么?

    let array_of_some_data: ({ some_value: number } | null)[] = [];

    //Getting Object is possible 'null' error as expected. Because I didn't check null before trying to access value.
    array_of_some_data[0].some_value = 5;

    //Not getting error as expected since I've checked null this time.
    if (array_of_some_data[0] !== null) array_of_some_data[0].some_value = 5;
    
    //Why am I getting Object is possible 'null' error here? Only difference from above line is I've stored index value in a const.
    const x: number = 0;
    if (array_of_some_data[x] !== null) array_of_some_data[x].some_value = 5;

【问题讨论】:

    标签: typescript syntax-error


    【解决方案1】:

    此问题是 typescript 的 control flow analysisdiscriminated unions 的限制。

    目前,我们可以使用诸如0 之类的文字来缩小对象(或者,在本例中为数组)的类型。但是,我们不能使用诸如x 之类的常量变量来执行此操作。出于性能考虑,Typescript 的开发人员决定不实现此功能。

    有一个公开的 PR 更详细地讨论了这个问题。 Here

    一种解决方法是通过使用中间分配来帮助打字稿:

    const x: number = 0;
    var element_of_some_data = array_of_some_data[x];
    if (element_of_some_data) element_of_some_data.some_value = 5;
    

    或者,使用 ! 运算符告诉 typescript 我们知道该值不为空:

    const x: number = 0;
    if (array_of_some_data[x] !== null) array_of_some_data[x]!.some_value = 5;
    

    【讨论】:

      猜你喜欢
      • 2021-06-06
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 2021-01-19
      • 2020-04-25
      • 2017-10-12
      • 1970-01-01
      • 2021-08-08
      相关资源
      最近更新 更多