reactjs 连接展开可选变量

bvn4nwqk  于 5个月前  发布在  React
关注(0)|答案(1)|浏览(47)

假设我们有一个可选字符串text的变量。有没有一种方法可以可选地打开这个属性?在Swift中,我们可以这样做:

guard let unwrappedText = text else { return }

字符串
在我们的代码中,我们有很多这样的东西:

if (!text) return


这很好,但稍后,text的类型仍然是一个可选字符串,所以我们仍然需要处理解包。理想情况下,我们可以同时检查null * 和 * 解包变量。我可能没有正确的术语,因为我似乎无法在网上找到任何关于TypeScript条件解包的内容。

hgc7kmma

hgc7kmma1#

TypeScript编译器足够智能,可以知道string | undefined等可选类型何时被缩小为精确类型。例如:

function foo(data?: string) {  // Here the type of data is string | undefined
    if (!data) return;

    data;  // Here the type of data is string
}

字符串
您可以在TypeScript playground上看到这一点:https://www.typescriptlang.org/play?ssl=5&ssc=2&pln=1&pc=1#code/GYVwdgxgLglg9mABMOcAUATAhlLB+ALkQGcoAnGMAcwEpEBvAKERcRmETQEJtc6yAplBBkwAbkbNWvLBIC+koA
Typescript中也有more explicit options for type narrowing

相关问题