Package Exports
- @httpx/plain-object
- @httpx/plain-object/package.json
Readme
@httpx/plain-object
Fast and lightweight (~80B) functions to check or assert that a value is a plain object.
Install
$ npm install @httpx/plain-object
$ yarn add @httpx/plain-object
$ pnpm add @httpx/plain-objectFeatures
- π Provide isPlainObject and assertPlainObject functions.
- π¦ Convenience PlainObject typescript typings.
- π Faster than most alternatives, see benchmarks.
- π Lightweight (starts at ~80B)
- π«Ά Inspired and compatible with @sindresorhus/is-plain-obj.
- π‘οΈ Tested on node 18-22, browser and runtime/edge.
- π Cross-realms tolerant (node:vm runInNewContext,...)
- ποΈ Available in ESM and CJS formats.
Documentation
π Official website or GitHub Readme
Usage
isPlainObject
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('({})')); // β
// β
π Static built-in classes are treated as plain objects
// check for `isStaticBuiltInClass` to exclude if needed
isPlainObject(Math); // β
isPlainObject(JSON); // β
isPlainObject(Atomics); // β
// βπ 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 {})); // β
isPlainObject(globalThis); // β,assertPlainObject
import { assertPlainObject } from '@httpx/plain-object';
import type { PlainObject } from '@httpx/plain-object';
function fn(value: unknown) {
// π Throws `new TypeError('Not a PlainObject')` if not a plain object
assertPlainObject(value);
// π Throws `new TypeError('Custom message')` if not a plain object
assertPlainObject(value, 'Custom message');
// π Throws custom error if not a plain object
assertPlainObject(value, () => {
throw new HttpBadRequest('Custom message');
});
return value;
}
try {
const value = fn({ key: 'value' });
// β
Value is known to be PlainObject<unknown>
assertType<PlainObject>(value);
} catch (error) {
console.error(error);
}isStaticBuiltInClass
info: Since v2.0.0
Since v2.0.0, isPlainObject will accept static built-in classes
as plain objects (Math, JSON, Atomics). If you need to exclude them,
a new typeguard has been created isStaticBuiltInClass.
import { isPlainObject, isStaticBuiltInClass } from '@httpx/plain-object';
const v = Math; // or Atomics or JSON
if (isPlainObject(v) && !isStaticBuiltInClass(v)) {
console.log('v is a plain object but not a static built-in class');
}PlainObject type
Generic
Γ¬sPlainObject and assertPlainObject accepts a generic to provide type
autocompletion. Be aware that no runtime check are done. If you're looking for
runtime validation, check zod, valibot or other alternatives.
import { isPlainObject } from '@httpx/plain-object';
import type { PlainObject } from '@httpx/plain-object';
type CustomType = {
id: number;
data?: {
test: string[];
attributes?: {
url?: string | null;
caption?: string | null;
alternativeText?: string | null;
} | null;
} | null;
};
const value = { id: 1 } as unknown;
if (isPlainObject<CustomType>(value)) {
// β
Value is a PlainObject with typescript autocompletion
// Note that there's no runtime checking of keys, so they are
// `unknown | undefined`. They will require unsing `?.` to access.
const url = value?.data?.attributes?.url; // autocompletion works
// β
url is `unknown | undefined`, so in order to use it, you'll need to
// manually check for the type.
if (typeof url === 'string') {
console.log(url.toUpperCase());
}
}PlainObject
import { assertPlainObject } from '@httpx/plain-object';
import type { PlainObject } from '@httpx/plain-object';
function someFn(value: PlainObject) {
//
}
const value = { key: 'value' } as unknown;
assertPlainObject(value);
someFn(value)Benchmarks
Performance is continuously monitored thanks to codspeed.io.
RUN v2.1.2 /home/sebastien/github/httpx/packages/plain-object
β bench/comparative.bench.ts (6) 4597ms
β Compare calling isPlainObject with 110x mixed types values (6) 4594ms
name hz min max mean p75 p99 p995 p999 rme samples
Β· @httpx/plain-object: `isPlainObject(v)` 1,806,371.37 0.0004 11.6450 0.0006 0.0005 0.0006 0.0007 0.0012 Β±6.82% 903186 fastest
Β· (sindresorhus/)is-plain-obj: `isPlainObj(v)` 1,598,094.82 0.0005 1.0909 0.0006 0.0006 0.0011 0.0013 0.0016 Β±0.92% 799048
Β· @sindresorhus/is: `is.plainObject(v)` 960,264.30 0.0009 5.9891 0.0010 0.0011 0.0011 0.0015 0.0033 Β±2.47% 480133
Β· estoolkit: `isPlainObject(v)` 127,719.90 0.0061 9.4934 0.0078 0.0077 0.0131 0.0215 0.0818 Β±3.89% 63860
Β· (jonschlinkert/)is-plain-object: `isPlainObject(v)` 817,269.76 0.0010 7.7567 0.0012 0.0012 0.0025 0.0028 0.0059 Β±3.97% 408635
Β· lodash-es: `_.isPlainObject(v)` 25,029.13 0.0341 11.9151 0.0400 0.0391 0.0574 0.0751 0.4693 Β±4.84% 12515 slowest
BENCH Summary
@httpx/plain-object: `isPlainObject(v)` - bench/comparative.bench.ts > Compare calling isPlainObject with 110x mixed types values
1.13x faster than (sindresorhus/)is-plain-obj: `isPlainObj(v)`
1.88x faster than @sindresorhus/is: `is.plainObject(v)`
2.21x faster than (jonschlinkert/)is-plain-object: `isPlainObject(v)`
14.14x faster than estoolkit: `isPlainObject(v)`
72.17x faster than lodash-es: `_.isPlainObject(v)`See benchmark file for details.
Bundle size
Bundle size is tracked by a size-limit configuration
| Scenario (esm) | Size (compressed) |
|---|---|
import { isPlainObject } from '@httpx/plain-object |
~ 80B |
import { assertPlainObject } from '@httpx/plain-object |
~ 134B |
Both isPlainObject and assertPlainObject |
~ 142B |
import { isStaticBuiltInClass } from '@httpx/plain-object |
~ 37B |
For CJS usage (not recommended) track the size on bundlephobia.
Compatibility
| Level | CI | Description |
|---|---|---|
| Node | β | CI for 18.x, 20.x & 22.x. |
| Browsers | β | > 96% on 07/2024. Mins to Chrome 96+, Firefox 90+, Edge 19+, iOS 12+, Safari 12+, Opera 77+ |
| Edge | β | Ensured on CI with @vercel/edge-runtime. |
| Typescript | β | TS 5.0 + / are-the-type-wrong checks on CI. |
| ES2022 | β | Dist files checked with es-check |
| Performance | β | Monitored with codspeed.io |
For older browsers: most frontend frameworks can transpile the library (ie: nextjs...)
Comparison with other libraries
@sindresorhus/is-plain-obj
This library wouldn't be possible without @sindresorhus is-plain-obj. Notable differences:
- SLightly faster (10%)
- ESM and CJS formats.
- Named export.
- Smaller bundle size.
- Provide a
PlainObjecttype andassertPlainObjectfunction. - Typescript convenience
PlainObjecttype.
Since v2, it diverges from is-plain-obj by
- Static built-in classes are considered as plain objects (use isStaticBuiltInClass to exclude).
-
[Symbol.iterator]is considered as a valid property for plain objects. -
[Symbol.toStringTag]is considered as a valid property for plain objects.`
Contributors
Contributions are welcome. Have a look to the CONTRIBUTING document.
Sponsors
If my OSS work brightens your day, let's take it to new heights together! Sponsor, coffee, or star β any gesture of support fuels my passion to improve. Thanks for being awesome! πβ€οΈ
Special thanks to
|
|
| JetBrains | Embie.be |
License
MIT Β© belgattitude and contributors.