@technically/is-not-null
v1.0.0
Published
A micro-package to check if a value is not null. With proper TS typing!
Downloads
4,775
Readme
@technically/is-not-null
@technically/is-not-null
is a micro-package to check if a value is not null. With proper TS typing!
Usage
import { isNotNull } from '@technically/is-not-null';
const values = ['hello', 'world', null];
const uppercase = values.filter(isNotNull).map((value) => {
return value.toUpperCase(); // OK
});
Why
In Typescript, it is often needed to filter out nulls from a list of values, and then process them.
The problem is that Boolean
does not currently work as a type-guard in Typescript:
const values = ['hello', 'world', null];
const uppercase = values.filter(Boolean).map((value) => {
return value.toUpperCase(); // TS18047: 'value' is possibly 'null'.
});
To mitigate the issue you have to wrap Boolean
into a type-guard function like this:
const values = ['hello', 'world', null];
const uppercase = values.filter((x): x is Exclude<typeof x, null>).map((value) => {
return value.toUpperCase(); // TS18047: 'value' is possibly 'null'.
});
To avoid writing these ad-hoc type-guards every time, I've created this package.
License
Credits
Authored by Ivan Voskoboinyk.