@axijs/ensure
v1.0.4
Published
A lightweight collection of TypeScript type guards and assertions
Readme
@axijs/ensure
A lightweight, zero-dependency collection of TypeScript type guards and assertions.
Designed to ensure type safety and handle runtime validation cleanly without the boilerplate.
Installation
npm install @axijs/ensure
# or
pnpm add @axijs/ensure
# or
yarn add @axijs/ensureFeatures
- Zero dependencies: Extremely lightweight.
- Strict Type Guards: Safely narrow down types (e.g.,
isObjectcorrectly filters outnulland arrays). - Assertion Utilities: Clean flow control with
throwIfandthrowIfEmpty.
Usage
1. Assertions & Flow Control
Use assertions to enforce conditions.
import {throwIfEmpty, throwIf, throwError} from '@axijs/ensure';
// Example: Narrowing a potentially undefined value
const user: { name: string } | undefined = findUser();
throwIfEmpty(user, 'User not found');
console.log(user.name);
// Example: Conditional throwing
const isInvalid = validate(data);
throwIf(isInvalid, 'Data validation failed');
// Example: Unconditional throw
function notImplemented(): never {
throwError('This feature is coming soon');
}2. Type Guards
Check types safely at runtime while giving TypeScript the correct type context.
import {isString, isObject, isPromise, isIterable} from '@axijs/ensure';
const data: unknown = fetchData();
if (isString(data)) {
console.log(data.toUpperCase());
}
if (isObject(data)) {
// True plain object (not null, not array)
console.log(Object.keys(data));
}
if (isPromise(data)) {
data.then(resolve);
}
if (isIterable(data)) {
for (const item of data) {
console.log(item);
}
}3. Emptiness Check
A pair of utilities to check whether a value is conceptually "empty" or not.
import {isEmpty, isNotEmpty} from '@axijs/ensure';
isEmpty({}); // true
isEmpty(0); // false
isEmpty(false); // false
isNotEmpty({name: 'Alex'}); // true
isNotEmpty([]); // false4. Value Normalization
Normalize values to a consistent format when an API accepts either a single value or an array of values.
import {ensureArray, toDelimitedString} from '@axijs/ensure';
ensureArray('item'); // ['item']
ensureArray(['one', 'two']); // ['one', 'two']
toDelimitedString('item'); // 'item'
toDelimitedString(['one', 'two']); // 'one/two'
toDelimitedString(['one', 'two'], ' | '); // 'one | two'API Documentation
For a complete list of available type guards, assertions, and their detailed descriptions, please visit the API Documentation.
License
MIT
