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

How to check for null value inline and throw an error in typescript?

在 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 working its way through the TC39 process, currently at Stage 2. If it gets to Stage 3 you can expect it will show up in TypeScript soon thereafter. (Update at the end of 2020: However, it seems to have stalled, having been blocked in Jan 2018 by a TC39 member who didn't think they "...were sufficiently motivated if we have do expressions..." Note that do expressions are still Stage 1 here at the end of 2020, but at least they were presented to TC39 in June.)

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

const myValue = someObject?.someProperty ?? throw new Error("custom error here");

或者如果您想要 someObject.someProperty.someProperty(我认为您的 C# 版本就是这样做的):

const myValue = (someObject?.someProperty ?? throw new Error("custom error here")).someProperty;

Babel 的 REPL 上有一个 Babel plugin for it you can use now. Here's the first example above


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

如果你想要 someObject.someProperty.someProperty,如果 someObjectnull/undefined 则没有错误,但如果 someObject.someProperty 是 [=22=,则会出现错误]/undefined,你可以这样做:

const myValue = someObject?.someProperty.someProperty;

有了那个:

  • 如果someObjectnullundefinedmyValue将得到值undefined
  • 如果 someObject 不是 nullundefinedsomeObject.somePropertynullundefined,您将得到一个错误,因为在第一个 someProperty.
  • 之后我们没有使用 ?.
  • 如果someObjectsomeObject.someProperty都不是nullundefinedmyValue会得到查找someObject.someProperty.someProperty的结果。

只要 TypeScript 本身不支持这个,你就可以编写一个类似于这个的函数:

function throwExpression(errorMessage: string): never {
  throw new Error(errorMessage);
}

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

const myString = nullableVariable ?? throwExpression("nullableVariable is null or undefined")

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

const test = null ?? (() => {throw new Error("Test is nullish")})();