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

问题描述 投票:1回答:1

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

var myValue = (someObject?.SomeProperty ?? throw new Exception("...")).SomeProperty;

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


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

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

  var myValue = someObject.someProperty.someProperty;

代码:

  var myValue = someObject?.someProperty.someProperty;

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

typescript syntax null null-check
1个回答
1
投票

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

JavaScript proposal for throw expressions正在TC39流程中进行,目前处于第2阶段。如果进入第3阶段(并且已经达到通常的标准,那么委员会可能会寻求共识,以便在下一次会议上取得进展),您可以期望它很快就会显示在TypeScript中。

[具有throw表达式,您可以编写此表达式(如果需要throw的值):

someObject.someProperty

或者如果您想要const myValue = someObject?.someProperty ?? throw new Error("custom error here"); (我认为您的C#版本就是这样:]

someObject.someProperty.someProperty

您现在可以使用const myValue = (someObject?.someProperty ?? throw new Error("custom error here")).someProperty; 。 Babel的REPL上的Babel plugin for it


旁注:您曾说过要抛出custom错误,但对于其他需要自定义错误的阅读此内容的人:

[如果要Here's the first example above,如果someObject.someProperty.somePropertysomeObject / null时没有错误,但是如果undefinedsomeObject.someProperty / null时出现错误,则可以执行以下操作:

undefined

带有那个:

  • 如果const myValue = someObject?.someProperty.someProperty; someObjectnull,则undefined将获得值myValue
  • 如果undefined不是someObjectnull,但undefinedsomeObject.somePropertynull,则会出现错误,因为在第一个undefined之后没有使用?.
  • 如果somePropertysomeObject都不是someObject.somePropertynull,则undefined将得到查找myValue的结果。
© www.soinside.com 2019 - 2024. All rights reserved.