如何内联检查空值并在打字稿中引发错误?

Val*_*ori 12 syntax null null-check typescript

在 C# 中,我可以编写代码来检查空引用,以防抛出自定义异常,例如:

var myValue = (someObject?.SomeProperty ?? throw new Exception("...")).SomeProperty;
Run Code Online (Sandbox Code Playgroud)

在最近的更新中,TypeScript 引入了空合并运算符 ?? 但是像上面的语句一样使用它会产生编译错误。TypeScript 中是否有一些类似的允许语法?


澄清一下,所需的行为是通过以下代码实现的:

  if(someObject?.someProperty == null) {
    throw new Error("...");
  }

  var myValue = someObject.someProperty.someProperty;
Run Code Online (Sandbox Code Playgroud)

编码:

  var myValue = someObject?.someProperty.someProperty;
Run Code Online (Sandbox Code Playgroud)

在逻辑上正常工作,但抛出一个意义不大的异常。

小智 19

如果您有兴趣在一行中抛出错误,您可以将其包装在立即调用的函数表达式中:

const test = null ?? (() => {throw new Error("Test is nullish")})();
Run Code Online (Sandbox Code Playgroud)


Mic*_*ier 18

只要 TypeScript 本身不支持此功能,您就可以编写一个与此类似的函数:

function throwExpression(errorMessage: string): never {
  throw new Error(errorMessage);
}
Run Code Online (Sandbox Code Playgroud)

这将允许您将错误作为表达式抛出:

const myString = nullableVariable ?? throwExpression("nullableVariable is null or undefined")
Run Code Online (Sandbox Code Playgroud)


T.J*_*der 10

语法错误的原因是这throw是一个语句,因此您不能将其用作运算符的操作数。

有一个关于throw表达式JavaScript 提案正在通过 TC39 过程,目前处于第 2 阶段。如果进入第 3 阶段,您可以预期它会在此后很快出现在 TypeScript 中。(2020 年底更新:然而,它似乎已经停滞,在 2018 年 1 月被一位 TC39 成员阻止,他认为他们“......如果我们有do表情就足够有动力......”请注意do表达式到 2020 年底仍然是第一阶段,但至少它们在 6 月提交给了 TC39 。)

使用throw表达式,您可以这样写(如果您想要 的值someObject.someProperty):

const myValue = someObject?.someProperty ?? throw new Error("custom error here");
Run Code Online (Sandbox Code Playgroud)

或者,如果您愿意someObject.someProperty.someProperty(这就是我认为您的 C# 版本所做的):

const myValue = (someObject?.someProperty ?? throw new Error("custom error here")).someProperty;
Run Code Online (Sandbox Code Playgroud)

你现在可以使用Babel 插件这是上面关于 Babel 的 REPL的第一个例子


旁注:您已经说过要抛出自定义错误,但是对于不需要自定义错误的其他人来说:

如果你想someObject.someProperty.someProperty,没有错误,如果someObjectnull/undefined但如果得到一个错误someObject.somePropertynull/ undefined,你可以这样做:

const myValue = someObject?.someProperty.someProperty;
Run Code Online (Sandbox Code Playgroud)

接着就,随即:

  • 如果someObjectnullor undefinedmyValue将得到值undefined
  • 如果someObjectis not nullor undefinedbut someObject.somePropertyis nullor undefined,你会得到一个错误,因为我们没有?.在第一个之后使用someProperty
  • 如果someObjectsomeObject.someProperty都不是nullundefinedmyValue将得到查找的结果someObject.someProperty.someProperty

  • 该提案没有取得进展,而且已经很长时间了......所以我会删除有关它很快取得进展的部分(在下次会议上) (2认同)