Skip to content

isDefined function ​

Checks whether a value is neither null nor undefined: the opposite of isNullish. isNotUndefined lets null through.

ts
import { isDefined } from 'utils';

Signature ​

ts
export function isDefined<T>(value: T): value is NonNullable<T>

Parameters ​

NameDescription
TThe type of the value.
valueThe value to check.

Returns ​

true when the value is present, 0, '' and false included.

Example ​

ts
[1, null, undefined].filter(isDefined); // [1], typed number[]

Tests ​

Line coverage: 100 %.

  • ✅ excludes null and undefined

Source ​

src/guard/is-defined.ts (on GitHub)

Source code
ts
/**
 * Checks whether a value is neither `null` nor `undefined`: the opposite of `isNullish`. `isNotUndefined` lets
 * `null` through.
 *
 * @template T - The type of the value.
 * @param value - The value to check.
 * @returns `true` when the value is present, `0`, `''` and `false` included.
 * @example
 * [1, null, undefined].filter(isDefined); // [1], typed number[]
 */
export function isDefined<T>(value: T): value is NonNullable<T> {
  // eslint-disable-next-line sonarjs/different-types-comparison -- `T` may include `undefined`.
  return value !== null && value !== undefined;
}
Test file
ts
import { isDefined } from './is-defined';

describe(isDefined, () => {
  it('excludes null and undefined', () => {
    expect([0, '', false, null, undefined, NaN].filter(isDefined)).toStrictEqual([0, '', false, NaN]);
  });
});

Keywords: is, defined, guards, function

Generated from the JSDoc of the sources.