Skip to content

Type safe utility functions for checking nullish values

License

Notifications You must be signed in to change notification settings

ewerk/null-or-undefined

Repository files navigation

@ewerk/null-or-undefined

NPM Version

Type safe utility functions for checking nullish values. It's dependency free and has no dependencies on external libraries.

Installation

You can install this package using npm:

npm install @ewerk/null-or-undefined

Usage

isNullOrUndefined

This function checks if a value is either null or undefined.

import { isNullOrUndefined } from '@ewerk/null-or-undefined';

const value = null;
if (isNullOrUndefined(value)) {
  console.log('Value is null or undefined');
}

neitherNullNorUndefined

This function checks if a value is neither null nor undefined. A neat use case is to filter out null and undefined values in RxJS observables.

import { neitherNullNorUndefined } from '@ewerk/null-or-undefined';

const value = 'Hello';
if (neitherNullNorUndefined(value)) {
  console.log('Value is neither null nor undefined');
}

// Example with RxJS
const value$: Observable<{title: string} | undefined> = of(undefined);

// before
const titleOld$: string = value$.pipe(
  filter((value) => value !== null && value !== undefined),
  map((value) => value as {title: string}), // cast is necessary to get rid of the undefined type
  map((value) => value.title),
);

// after
const titleNew$: string = value$.pipe(
  filter(neitherNullNorUndefined),
  map((value) => value.title)
);

hasEmptyValue

This function checks if a value is considered "empty". A value is considered empty if it is an empty array, null, undefined, or an empty string. This function could be useful for validating user input.

import { hasEmptyValue } from '@ewerk/null-or-undefined';

console.log(hasEmptyValue('')); // true
console.log(hasEmptyValue([])); // true
console.log(hasEmptyValue(null)); // true
console.log(hasEmptyValue(undefined)); // true

console.log(hasEmptyValue(false)); // false
console.log(hasEmptyValue(0)); // false
console.log(hasEmptyValue('test string')); // false
console.log(hasEmptyValue(['test', 'string'])); // false

Contributing

Contributions are welcome! Please open an issue or submit a pull request on GitHub.

License

This project is licensed under the MIT License.

Author

Florian Symanowski (@iceteabottle)

Contributors

Links