在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;
在逻辑上可以正常工作,但抛出意义不大的异常。
语法错误的原因是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.someProperty
为someObject
/ null
时没有错误,但是如果undefined
为someObject.someProperty
/ null
时出现错误,则可以执行以下操作:
undefined
带有那个:
const myValue = someObject?.someProperty.someProperty;
是someObject
或null
,则undefined
将获得值myValue
undefined
不是someObject
或null
,但undefined
是someObject.someProperty
或null
,则会出现错误,因为在第一个undefined
之后没有使用?.
。 someProperty
和someObject
都不是someObject.someProperty
或null
,则undefined
将得到查找myValue
的结果。