Skip to content

isNonEmpty

Checks if an array is non-empty (has at least one element). null and undefined are treated as empty arrays and return false.

Available since v2.0.3

import { isNonEmpty } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { isNonEmpty } from 'helpers4/array';
isNonEmpty<T>(value: readonly T[] | null | undefined): value is readonly [T, T]
ParameterTypeDescription
valuereadonly T[] | null | undefinedThe array to check

value is readonly [T, T] — true if the array has at least one element; false for empty, null, or undefined

Returns true for arrays with at least one element, regardless of the element values.

isNonEmpty([1, 2, 3]) // => true
isNonEmpty([null])    // => true  (null is still an element)
isNonEmpty([])        // => false

Safe first-element access with type narrowing

Section titled “Safe first-element access with type narrowing”

In the true branch, the type narrows to [T, …T[]], making arr[0] always defined.

function first<T>(arr: readonly T[]): T | undefined {
  if (isNonEmpty(arr)) return arr[0]; // arr[0] is T, not T | undefined
  return undefined;
}
first([1, 2]) // => 1
first([])     // => undefined

View source on GitHub