@httpx/assert
Version:
Assertions and typeguards
67 lines (64 loc) • 2.82 kB
TypeScript
import { B as BasePlainObject, D as DefaultBasePlainObject, P as PlainObject } from './object.types-FqVyteL0.js';
import './internal.types-D5VRBw-5.js';
/**
* Check if a value is a plain object
*
* A plain object is a basic JavaScript object, such as {}, { data: [] }, new Object() or Object.create(null).
*
* @example
* ```typescript
* import { isPlainObject } from '@httpx/plain-object';
*
* // ✅👇 True
*
* isPlainObject({ }); // ✅
* isPlainObject({ key: 'value' }); // ✅
* isPlainObject({ key: new Date() }); // ✅
* isPlainObject(new Object()); // ✅
* isPlainObject(Object.create(null)); // ✅
* isPlainObject({ nested: { key: true} }); // ✅
* isPlainObject(new Proxy({}, {})); // ✅
* isPlainObject({ [Symbol('tag')]: 'A' }); // ✅
*
* // ✅👇 (node context, workers, ...)
* const runInNewContext = await import('node:vm').then(
* (mod) => mod.runInNewContext
* );
* isPlainObject(runInNewContext('({})')); // ✅
*
* // ❌👇 False
*
* class Test { };
* isPlainObject(new Test()) // ❌
* isPlainObject(10); // ❌
* isPlainObject(null); // ❌
* isPlainObject('hello'); // ❌
* isPlainObject([]); // ❌
* isPlainObject(new Date()); // ❌
* isPlainObject(new Uint8Array([1])); // ❌
* isPlainObject(Buffer.from('ABC')); // ❌
* isPlainObject(Promise.resolve({})); // ❌
* isPlainObject(Object.create({})); // ❌
* isPlainObject(new (class Cls {})); // ❌
*
* // ⚠️ Edge cases
* //
* // 👇 globalThis isn't properly portable across all JS environments
* //
*
* isPlainObject(globalThis); // ✅ with Bun ❌ otherwise (browser, Nodejs, edge, cloudflare)
*
* // 👇 Static built-in classes aren't properly checked. This is a trade-off
* // to maintain the best performance and size. If you need to check for these,
* // use a custom type guard. But in most cases, you won't need to check for these
* // as the probability of writing a code that receives these as plain objects is low.
* // and probably indicates an issue in your code.
*
* isPlainObject(Math); // ⚠️✅ return true, but Math is not a plain object
* isPlainObject(JSON); // ⚠️✅ return true, but JSON is not a plain object
* isPlainObject(Atomics); // ⚠️✅ return true, but Atomics is not a plain object
* isPlainObject(Reflect); // ⚠️✅ return true, but Reflect is not a plain object
* ```
*/
declare const isPlainObject: <TValue extends BasePlainObject = DefaultBasePlainObject>(v: unknown) => v is TValue extends DefaultBasePlainObject ? BasePlainObject : PlainObject<TValue>;
export { isPlainObject };