@pcg/predicates
v2.0.0
Published
Type predicate utilities and assertions
Readme
@pcg/predicates
Type guards and small helpers for checking values at runtime: primitives, objects, arrays and empty containers. Each guard narrows the TypeScript type of its argument.
Installation
pnpm add @pcg/predicatesThe package has no peer dependencies.
Requirements
- Node.js 26 or later.
- ESM only: the package is published as an ES module (
"type": "module") with its own TypeScript declarations.
Usage
import {
entriesOf,
isEmptyContainer,
isNullOrUndefined,
isPlainObject,
isString,
type Maybe,
} from '@pcg/predicates';
const describe = (value: unknown): string => {
if (isNullOrUndefined(value)) {
return 'nothing';
}
if (isString(value)) {
return value.toUpperCase(); // value is string here
}
if (isPlainObject(value)) {
return Object.keys(value).join(', '); // value is Record<string, unknown> here
}
return String(value);
};
describe({ name: 'Jane Doe', company: 'Acme' }); // 'name, company'
isEmptyContainer({}); // true
isEmptyContainer([1, 2, 3]); // false
// Typed alternative to Object.entries()
const limits = { daily: 10, monthly: 200 };
for (const [key, value] of entriesOf(limits)) {
// key: 'daily' | 'monthly', value: number
}
const nickname: Maybe<string> = undefined;API
Primitives
isString(value)–truefor a string.isNumber(value)–truefor a number.isCallable(value)–truefor a function.isNullOrUndefined(value)–truefornullandundefined.isIndex(value)–truefor a non-negative number or a string that converts to one (2,'2'); used to tell array indexes from object keys.
Objects and arrays
isObject(value)–truefor any non-null object except an array (class instances andDateincluded).isPlainObject(value)–truefor an object created by{},new Object()orObject.create(null).isContainerValue(value)–truefor an object or an array.isEmptyArray(value)–truefor an array of length 0.isEmptyContainer(value)–truefor an empty array or an object without own keys.keysOf(object)–Object.keys()typed as(keyof T)[].entriesOf(object)–Object.entries()typed withEntries<T>fromtype-fest.
Types
Maybe<T>–T | undefined.MaybeNull<T>–T | null.
License
MIT
