[英]How to declare "is not null" type assertion using Typescript 3.7 Assertion Functions
目前我正在使用以下斷言功能。
// 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
不為null
// this `is not` invalid syntax
declare function isNotNull(value: unknown): asserts value is not null
這在 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}`
);
}
}
注意:Typescript 站點上的示例使用AssertionError
,但該示例在 3.7.2 中無法正常工作,因此將其更改為普通的Error
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.