代码之家  ›  专栏  ›  技术社区  ›  s1n7ax

如何使用Typescript 3.7断言函数声明“is not null”类型断言

  •  1
  • s1n7ax  · 技术社区  · 5 年前

    目前我正在使用以下断言函数。

    // declare
    declare function assert(value: unknown): asserts value;
    
    // use
    assert(topPort !== null);
    assert(bottomPort !== null);
    assert(leftPort !== null);
    assert(rightPort !== null);
    

    我知道可以查一下 null 通过跟踪,

    declare function isNull(value: unknown): asserts value is null
    let a = null;
    isNull(a)
    

    但是,我该怎么检查 value 不是 无效的

    // this `is not` invalid syntax
    declare function isNotNull(value: unknown): asserts value is not null
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   crashmstr    5 年前

    这在 Assertion Functions 在3.7中新增的部分,并使用 NonNullable 实用类。

    function assertIsDefined<T>(val: T): asserts val is NonNullable<T> {
        if (val === undefined || val === null) {
            throw new AssertionError(
                `Expected 'val' to be defined, but received ${val}`
            );
        }
    }