【发布时间】:2020-07-08 02:23:00
【问题描述】:
在 C# 中,我可以编写代码来检查空引用并以防引发自定义异常,例如:
var myValue = (someObject?.SomeProperty ?? throw new Exception("...")).SomeProperty;
在最近的更新中,TypeScript 引入了 null 合并运算符 ??但是像上面的语句一样使用它会产生编译错误。 TypeScript 中是否有一些类似的允许语法?
为了澄清,所需的行为是通过以下代码实现的:
if(someObject?.someProperty == null) {
throw new Error("...");
}
var myValue = someObject.someProperty.someProperty;
代码:
var myValue = someObject?.someProperty.someProperty;
逻辑上工作正常,但抛出一个意义不大的异常。
【问题讨论】:
-
C# 版本不应该只是
var myValue = someObject?.SomeProperty ?? throw new Exception("...");吗?或者你想得到someObject.SomeProperty.SomeProperty?
标签: typescript syntax null null-check