【问题标题】:How to check for null value inline and throw an error in typescript?如何检查内联空值并在打字稿中抛出错误?
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

    • 一个 throw 辅助函数是一个有趣的方法,感谢分享!
    • 非常好!感谢您的回答。
    【解决方案3】:

    语法错误的原因是throw是一个语句,所以不能把它作为操作符的操作数。

    有一个JavaScript proposal for throw expressions 正在通过 TC39 流程,目前处于第 2 阶段。如果它进入第 3 阶段,您可以预期它很快就会出现在 TypeScript 中。 (2020 年底更新:然而,它似乎已经停滞不前了,被一个 TC39 成员 blocked in Jan 2018 认为他们 “......如果我们有 do 表达式,就会有足够的动力...... .” 请注意,do 表达式在 2020 年底仍处于第 1 阶段,但至少它们已提交给 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 plugin for itHere's the first example above 在 Babel 的 REPL 上。


    旁注:您说过要抛出 custom 错误,但对于其他不需要自定义错误的阅读本文的人:

    如果你想要someObject.someProperty.someProperty,如果someObjectnull/undefined 没有错误,但如果someObject.somePropertynull/undefined 则会出错,你可以这样做:

    const myValue = someObject?.someProperty.someProperty;
    

    这样:

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

    【讨论】:

    • 提案没有进展,已经很久了......所以我会尽快删除关于它推进的部分(在下次会议上)
    • @Yepeekai - 是的,最后一次出现在 2018 年,无法达成共识以进入第 3 阶段,同时其原因(do 表达式)仍处于第 1 阶段。但至少 @987654363 @ 表达式在 2020 年 6 月的会议上提出。
    猜你喜欢
    • 2023-02-20
    • 2017-11-25
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 2020-09-24
    • 2021-08-03
    相关资源
    最近更新 更多