【问题标题】:How to use Typescript Optional Chaining feature with Early Exit construct to rule out nulls along the way如何使用带有 Early Exit 结构的 Typescript 可选链接功能来排除空值
【发布时间】:2021-05-19 02:17:06
【问题描述】:

有这个sn-p

interface Bar{
    a: A|null
}
interface A {
    text: string
}

function foo(bar: Bar) {
    if(bar.a?.text === null) {
        return;
    }

    console.log(bar.a.text);
}

为什么 Typescript 抱怨 bar.a 在与 console.log 的行上可能为空

对象可能是“空”。

当我已经检查了上面的null 并通过提前退出排除了它?

如果bar.a?.text 不是null,则意味着a 不是null 它是函数的上下文。

在这个例子中看起来没什么大不了的,但是使用可选链来排除a?.b?.c?.d?.text中的所有nulls

TS Playground (v4.2)

【问题讨论】:

    标签: typescript


    【解决方案1】:

    该错误实际上应该是“对象可能是'未定义'”。而 bar.a.text 必须是 stringbar.a 可以是 typeof A null,如果 bar.anull,则 bar.a?.text 可能为 undefined。只需使用相等运算符 (==) 而不是严格相等运算符 (===) 将您的检查更改为“无效”检查。

    function foo(bar: Bar) {
        if(bar.a?.text == null) { // nullish check isntead of strict null check.
            return;
        }
        console.log(bar.a.text);
    }
    

    是的,bar.a?.text 可以返回 undefined 似乎有点傻,因为这些值都不应该是 undefined 在严格模式下,但这就是运算符的工作方式 - 当遇到空值时返回 undefined。如果您使用 console.log(bar.a?.text) 对其进行测试,您会发现即使 bar.anull 返回的结果将是未定义。这与 MDN 的 Optional Chaining (?.) 章节中描述的操作符行为一致。

    如果你想保持严格的相等检查,不要使用可选的链接运算符,只需检查 bar.a 是否为 null

       if(bar.a === null) {
           return;
       }
       console.log(bar.a.text); // all good since text can never be null.
    

    【讨论】:

      猜你喜欢
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 2020-03-02
      • 1970-01-01
      • 2014-10-07
      • 2016-04-30
      • 1970-01-01
      相关资源
      最近更新 更多