Skip to content
VersionSize

isObject

Checks if a value is a plain object.

Implementation

View Source Code
ts
/**
 * Determines if the passed value is an object.
 *
 * @example
 * ```ts
 * const value = { key: 'value' };
 * isObject(value); // true
 * isObject('hello world'); // false
 * isObject(value, 1); // false
 * isObject(value, value); // true
 * ```
 *
 * @param arg - The argument to be checked.
 *
 * @returns `true` if the value is an object, else `false`.
 */
export function isObject(arg: unknown): arg is object {
  return typeof arg === 'object' && arg !== null && !Array.isArray(arg);
}

export const IS_OBJECT_ERROR_MSG = 'Expected an object';

Features

  • Type Guard: Narrows unknown to object
  • Plain Object Detection: Excludes arrays, functions, and null
  • Isomorphic: Works in both Browser and Node.js

API

ts
function isObject(value: unknown): value is object;

Parameters

  • value: The value to check

Returns

  • true if the value is a plain object, false otherwise

Examples

Basic Usage

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

isObject({}); // true
isObject({ name: 'Alice' }); // true
isObject([]); // false
isObject(null); // false
isObject(new Date()); // true

Type Guard Usage

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

function process(value: unknown) {
  if (isObject(value)) {
    // TypeScript knows value is object here
    return Object.keys(value);
  }
  return [];
}

Implementation Notes

  • Returns false for arrays (use isArray for arrays)
  • Returns false for functions (use isFunction for functions)
  • Returns false for null (common JavaScript gotcha)
  • Returns true for class instances and built-in objects like Date, RegExp

See Also