requireNotNull alternative in TypeScript for null safety

Viewed 33

I recently started learning Kotlin and was wondering if TypeScript has a requireNotNull similar check or method?

I'm using a function getUserId() which either return a string or null.

const userId = getUserId()

MakeNetworkFetch(userId) // could be nulll

// Also at the moment I'm using this below code, which makes Typescript linter happy

MakeNetworkFetch(userId!!)

I tried searching for Double-bang after variable but could not find anything

1 Answers

Kotlin's requireNotNull throws an IllegalArgumentException upon receiving a null value. In TypeScript, you could use an assertion function with NonNullable<T> to get the same behavior:

function requireNotNull<T>(value: T): asserts value is NonNullable<T> {
  if (value === null || value === undefined) {
    throw Error('Value is null');
  }
}

And then:

requireNotNull(userId);
makeNetworkFetch(userId); // type of userId inferred as string at compile time
                          // value of userId guaranteed to be non-null at runtime

The difference between this and the non-null assertion operator (userId!), is that the assertion function remains present in the compiled JavaScript, so a null value will trigger the error, and will not be passed down to the method.

Related