s1n7ax
s1n7ax

Reputation: 3069

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,

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

But, how do I check value is not null

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

Upvotes: 1

Views: 591

Answers (1)

crashmstr
crashmstr

Reputation: 28573

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.

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.

Upvotes: 2

Related Questions