Skip to content

isDefined

Checks if a value is defined (not undefined nor null). This is the inverse of isNullish.

Use as a type-safe filter callback to remove null/undefined from arrays.

Available since v2.0.0

import { isDefined } from '@helpers4/type';
isDefined<T>(value: Maybe<T>): value is T
ParameterTypeDescription
valueMaybe<T>The value to check

value is T — True if value is not undefined nor null

isDefined(42)        // => true
isDefined('')        // => true (empty string is defined)
isDefined(null)      // => false
isDefined(undefined) // => false
// Type-safe alternative to filter out null/undefined
const items: (string | null | undefined)[] = ['a', null, 'b', undefined];
const result = items.filter(isDefined);
// => ['a', 'b'] with type string[]

Type for values that can be T, undefined, or null.

type Maybe<T> = T | undefined | null

View source on GitHub