【问题标题】:Using strictNullChecks is there a way to assert non-null inline with code without if statement使用 strictNullChecks 有没有一种方法可以在没有 if 语句的情况下用代码断言非空内联
【发布时间】:2017-05-06 06:06:49
【问题描述】:

我最近为我们的代码启用了 strictNullChecks。我想写一个断言助手,它可以内联用于我们不应该有 null 但类型仍然有 null 作为可能值的地方。

类似:

doSomething() {
    assertNonNull(this.obj);  // throws exception if null
    this.obj.doMore();
}

我知道我可以使用 this.obj!.doMore() 来做到这一点,但我希望让运行时断言来验证它,然后让 typescript 知道在该断言之后类型联合不再包含 null。

是否可以编写这样的辅助函数?到目前为止,我似乎无法提出任何建议。

【问题讨论】:

    标签: typescript typescript2.0


    【解决方案1】:

    你可以让 assertNonNull 返回它的参数,当它为非空时适当地输入,或者以其他方式抛出:

    function assertNonNull<T>(x: T | null | undefined): T {
        if (x === null || x === undefined) {
            throw new Error('non-null assertion failed');
        } else {
            return x;
        }  
    }
    

    那么你可以这样使用它:

    class Foo {
    
        obj: { doMore() } | null;
    
        doSomething() {
            assertNonNull(this.obj).doMore();
        }
    }
    

    【讨论】:

    • 不漂亮,但绝对适合我的情况。我很想看到 typescript 添加一些东西,使它更容易表达。
    【解决方案2】:

    不,目前这是不可能的(据我所知),因为该语言不支持错误抛出。

    你可以做的是:

    class MyClass {
        private obj: { doMore(): void } | null;
    
        doSomething() {
            if (assertNonNull(this.obj)) {
                this.obj.doMore(); // this.obj is not null here
            }
        }
    }
    
    function assertNonNull(obj: { doMore(): void } | null): obj is { doMore(): void } {
        return obj != null;
    }
    

    (code in playground)

    您也可以这样做:

    doSomething() {
        if (!assertNonNull(this.obj)) {
            throw new Error("obj is null");
        }
    
        this.obj.doMore(); // this.obj is not null here
    }
    

    但是你不能有基于抛出错误的类型保护。
    如果添加我要求的功能应该是可能的:throws clause and typed catch clause

    您可以将您的场景添加到问题中,它显示了它的另一种用法。

    【讨论】:

      猜你喜欢
      • 2022-11-21
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 2019-03-06
      相关资源
      最近更新 更多