CyrefJS
CCyrefJS
فا
Back to documentation
Type/Since 1.38.0

isPlainObject

Checks whether a value is a plain object with Object.prototype or null as its prototype.

isPlainObject(value):value is Record<PropertyKey, unknown>

Behavior

The function first rejects null and values whose typeof result is not object. It then checks the object's prototype and returns true only when the prototype is Object.prototype or null.

Prototype Check

Objects created with object literals or new Object() normally have Object.prototype as their prototype. Objects created with Object.create(null) have a null prototype and are also accepted.

Non-Plain Objects

Arrays, Date instances, Map instances, Set instances, and instances of custom classes are not considered plain objects because their prototypes differ from Object.prototype and null.

Type Guard

The return type is value is Record<PropertyKey, unknown>, allowing TypeScript to narrow the value to a key-value object inside a conditional branch.

Parameters

valueunknownrequired

The value to check.

Returns

value is Record<PropertyKey, unknown>

Returns true when the value is an object whose prototype is Object.prototype or null.

Examples

01

Basic usage

Check whether different values are plain objects.

TypeScript
import { isPlainObject } from "@cyref/js";

isPlainObject({});
// true

isPlainObject({ name: "Amir" });
// true

isPlainObject(Object.create(null));
// true

isPlainObject([]);
// false

isPlainObject(new Date());
// false

isPlainObject(null);
// false

isPlainObject("hello");
// false
02

Type narrowing

isPlainObject acts as a TypeScript type guard and narrows the value to Record<PropertyKey, unknown> when it returns true.

TypeScript
const value: unknown = {
  name: "Amir",
};

if (isPlainObject(value)) {
  console.log(value.name);
}
03

Objects with null prototypes

Objects created with Object.create(null) are considered plain objects by this function.

TypeScript
const value = Object.create(null);

isPlainObject(value);
// true
Built with@cyref/js·Official documentation