Skip to content
VersionSize

isNil

The isNil utility is a type guard that checks if a value is strictly null or undefined. It is the inverse of isDefined and is useful for identifying missing or uninitialized data.

Implementation

View Source Code
ts
/**
 * Determines if the passed value is null or undefined.
 *
 * @example
 * ```ts
 * isNil(null); // true
 * isNil(undefined); // true
 * isNil(''); // false
 * isNil(0); // false
 * ```
 *
 * @param arg - The argument to be checked.
 *
 * @returns `true` if the value is null or undefined, else `false`.
 */
export function isNil(arg: unknown): arg is null | undefined {
  return arg === undefined || arg === null;
}

export const IS_NIL_ERROR_MSG = 'Expected a null or undefined value';

Features

  • Isomorphic: Works in both Browser and Node.js.
  • Type Guard: Automatically narrows types to null | undefined within conditional blocks.
  • Precise: Correctly identifies that 0, false, and '' are NOT nil.

API

ts
function isNil(value: unknown): value is null | undefined;

Parameters

  • value: The value to check.

Returns

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

Examples

Basic Usage

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

isNil(null); // true
isNil(undefined); // true
isNil(0); // false
isNil(''); // false
isNil(false); // false

Type Guarding

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

function cleanup(text: string | null | undefined) {
  if (isNil(text)) {
    return 'default';
  }
  // text is now narrowed to 'string'
  return text.trim();
}

Implementation Notes

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

See Also

  • isDefined: The inverse check (returns true for defined values).
  • isEmpty: Check if a value is empty (broader than just nil).
  • isArray: Dedicated array type guard.