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
unknowntoobject - 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
trueif the value is a plain object,falseotherwise
Examples
Basic Usage
ts
import { isObject } from '@vielzeug/toolkit';
isObject({}); // true
isObject({ name: 'Alice' }); // true
isObject([]); // false
isObject(null); // false
isObject(new Date()); // trueType 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
falsefor arrays (useisArrayfor arrays) - Returns
falsefor functions (useisFunctionfor functions) - Returns
falsefornull(common JavaScript gotcha) - Returns
truefor class instances and built-in objects likeDate,RegExp
See Also
- isArray: Check if value is an array
- isFunction: Check if value is a function
- isPrimitive: Check if value is a primitive type
- typeOf: Get the type of any value