简体   繁体   English

如何使用 Typescript 3.7 断言函数声明“不为空”类型断言

[英]How to declare "is not null" type assertion using Typescript 3.7 Assertion Functions

Currently I'm using following assertion function.目前我正在使用以下断言功能。

// declare
declare function assert(value: unknown): asserts value;

// use
assert(topPort !== null);
assert(bottomPort !== null);
assert(leftPort !== null);
assert(rightPort !== null);

I know it's possible to check is null by following,我知道可以通过以下方式检查是否null

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

But, how do I check value is not null但是,我如何检查value不为null

// this `is not` invalid syntax
declare function isNotNull(value: unknown): asserts value is not null

This is indicated at the bottom of the Assertion Functions section of the What's New in 3.7, and uses the NonNullable utility class.这在 3.7 中的新增功能断言函数部分的底部指示,并使用NonNullable实用程序类。

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

Note: the example on the Typescript site uses AssertionError , but the example does not work as-is in 3.7.2, so changing it to a plain Error .注意:Typescript 站点上的示例使用AssertionError ,但该示例在 3.7.2 中无法正常工作,因此将其更改为普通的Error

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM