Aller au contenu principal

isPlainObject()

isPlainObject(value): value is Record<string, any>

Checks if a value is a plain object (object literal or Object.create(null)).

💎 Why is this a Hidden Gem?

Distinguishes true dictionaries from arrays, null, or class instances.

remarque

Excludes arrays, Date, Map, Set, class instances, etc. Only {}, new Object(), and Object.create(null).


Parameters

value: unknown

The value to check.


Returns: value is Record<string, any>

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


See Also

isObject


Since

1.0.0


Example

isPlainObject({});                    // => true
isPlainObject({ a: 1 }); // => true
isPlainObject(new Object()); // => true
isPlainObject(Object.create(null)); // => true
isPlainObject([]); // => false
isPlainObject(new Date()); // => false
isPlainObject(new Map()); // => false
isPlainObject(new (class Foo {})()); // => false
isPlainObject(null); // => false

How it works?

Type guard that checks if a value is a plain object (object literal or Object.create(null)).

What Qualifies

ValueResultReason
{} trueObject literal
{ a: 1 } trueObject literal
new Object() trueObject constructor
Object.create(null) trueNull prototype
[] falseArray
new Date() falseDate instance
new Map() falseMap instance
new MyClass() falseClass instance
null falseNot an object

isPlainObject vs isObject


Use Cases

Identify configuration objects 📌

Ensure a value is a simple dictionary {} and not a complex object instance. Perfect for merging configs or validating JSON payloads.

if (isPlainObject(config)) {
// Safe to merge or spread
const merged = { ...defaultConfig, ...config };
}

Deep clone decision logic

Determine if a value needs recursive cloning or can be copied by reference.

function deepClone(value: unknown): unknown {
if (!isPlainObject(value)) {
return value; // Primitives, arrays handled elsewhere, class instances kept as-is
}

const result: Record<string, unknown> = {};
for (const key in value) {
result[key] = deepClone(value[key]);
}
return result;
}