@technically/is-not-null
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

@technically/is-not-null

Test

@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

MIT

Credits

Authored by Ivan Voskoboinyk.

Package Sidebar

Install

npm i @technically/is-not-null

Weekly Downloads

1,327

Version

1.0.0

License

MIT

Unpacked Size

3.92 kB

Total Files

6

Last publish

Collaborators

  • e1npm