Skip to content
VersionSize

isDefined

The isDefined utility is a type guard that checks if a value is NOT undefined or null. It is essential for safely handling optional values and cleaning up data sets.

Implementation

View Source Code
ts
/**
 * Checks if a value is defined (not `undefined`).
 *
 * @example
 * ```ts
 * isDefined(123); // true
 * isDefined(undefined); // false
 * isDefined('hello world'); // true
 * isDefined({}); // true
 * isDefined([]); // true
 * isDefined(null); // true
 * ```
 *
 * @param arg - The value to check.
 *
 * @returns `true` if the value is defined, else `false`.
 */
export function isDefined<T>(arg: T | undefined): arg is T {
  return arg !== undefined;
}

Features

  • Isomorphic: Works in both Browser and Node.js.
  • Type Guard: Automatically narrows types to exclude null and undefined.
  • Durable: Unlike a simple truthiness check, it correctly identifies 0, false, and '' as defined values.

API

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

Parameters

  • value: The value to check.

Returns

  • true if the value is neither null nor undefined; otherwise, false.

Examples

Basic Usage

ts
import { isDefined } from '@vielzeug/toolkit';

isDefined('hello'); // true
isDefined(0); // true
isDefined(false); // true
isDefined(null); // false
isDefined(undefined); // false

Filtering Arrays

ts
import { isDefined, filter } from '@vielzeug/toolkit';

const data = ['a', undefined, 'b', null, 'c'];

// TypeScript correctly infers the result as string[]
const cleanData = filter(data, isDefined);
// ['a', 'b', 'c']

Implementation Notes

  • Returns true if value !== undefined && value !== null.
  • Throws nothing; safe for any input type.

See Also

  • isNil: The inverse check (returns true for null/undefined).
  • isEmpty: Check if a value is empty (includes length checks).
  • compact: Remove all falsy values from an array.