2.0.0-alpha2 • Published 2 years ago

utility-guards v2.0.0-alpha2

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

Features:

  • šŸ› ļø Reliable type checking for JS runtime
  • šŸ“¦ Zero dependencies and only ~800 bytes gzipped size
  • šŸ“¦ tree-shaking friendly
  • šŸ”© Full Typescript guard support
  • šŸ”© Isomorphic: works in browser and node.js
  • šŸ”‘ Addon: validate and validateStrict validators for runtime values (object) validation
npm install utility-guards

Usage

// Using default import – `is` namespace object
import is from 'utility-guards';

is.String('42'); // true
is.Number(42); // false
is.$not(is.Nil)(0); // true
// using named imports (tree-shaking friendly)
import { isString, isNumber, isNil, $not } from 'utility-guards';

isString('42'); // true
isNumber(42); // false

isString('42'); // true
isNumber(42); // false
$not(isNil)(0); // true
// using standalone imports (tree-shaking friendly)
import isString from 'utility-guards/isString';
import isNumber from 'utility-guards/isNumber';
import isNil from 'utility-guards/isNil';
import $not from 'utility-guards/$not';

isString('42'); // true
isNumber(42); // false
$not(isNil)(0); // true

Guards

isString(value) – Check if value a string literal or string created by String constructor

isNumber(value) – Check if value a number literal or number created by Number constructor

isBoolean(value) – Check if value a boolean

isNaN(value) – Check if value a NaN value

isUndefined(value) – Check if value is a undefined

isNull(value) – Check if value is a null

isNil(value) – Check if value is a null or undefined

isPrimitive(value) – Check if value is a primitive

isSymbol(value) – Check if value is a Symbol

isRegExp(value) – Check if value is a RegExp object or RegExp literal

isError(value) – Check if value is an JS Error object

isAnyObject(value) – Check if value is a language type object (except null)

isPlainObject(value) – Check if value is a plain JavaScript object

isArray(value) – Check if value is array

isFunction(value) – Check if value is an any function (except class definition)

isClass(value) – Check if value is a class definition

isPromise(value) – Check if value is a promise object

isPromiseLike(value) – Check if value is a promise-like object (has then method)

isIterable(value) – Check if value is iterable (arrays, strings, maps, sets, etc.)

isDate(value) – Check if value is a valid JS Date object

isHasProperty(obj, propertyName) – Check if an object has a property

isArrayOf(array, guard) – Check if all elements of array match given guard

isInstanceOf(value, constructor) – Check if value is instance of given constructor

isEmpty(value) – Check if value is empty.

Value is considered as empty if it's:

  • Empty object: {}
  • Empty array: []
  • Empty Map: new Map()
  • Empty Set: new Set()
  • Empty string: ''
  • Nullable value: null or undefined

All methods that starts with $ are utility methods for manipulating with guards

$not – Inverse given guard

import { $not } from 'utility-guards'; // or is.$not if you use default import
const notIsNil = $not(is.Nil);

const arr = [1, null, 2, undefined, 3];
const filtered = arr.filter(notIsNil);

console.log(filtered); // [1, 2, 3] (type: number[])

$some – Combine multiple guards with some logic (logical OR)

import { $some, isNumber, isString } from 'utility-guards';

const isNumberOrString = $some(isNumber, isString);

isNumberOrString(42); // true
isNumberOrString('42'); // true
isNumberOrString(true); // false

$every – Combine multiple guards with every logic (logical AND)

import { $every, isNumber, isArray } from 'utility-guards';

const isEmptyArray = $every(isArray, isEmpty);

isEmptyArray([]); // true
isEmptyArray([1, 2, 3]); // false

is as a function guard

You can use is as a function guard. It will check if value is equal to a given expected value.

Based on Object.is method for comparison

import is from 'utility-guards';

is(42, 42); // true

const isNumber42 = is(42);
isNumber42(42); // true

Curried guards

ā„¹ļø Guards with extra arguments are curried functions

is.ArrayOf(42, is.Number); // valid
is.ArrayOf(is.Number)(42); // also valid

is.InstanceOf(null!, ArrayBuffer); // valid
is.InstanceOf(ArrayBuffer)(null!); // also valid

validate addon

Allows to validate runtime values (objects) with given schema or guard

Usage

import { validate } from 'utility-guards';
import validate from 'utility-guards/validate';
const obj = JSON.parse('...');

const schema = {
    a: isNumber,
    b: $some(isString, isNil), // string or nil
    c: {
        d: isBoolean,
        e: {
            f: isNumber,
            g: isString,
        },
    },
};

if (validate(obj, schema)) {
    obj.c.e.f; // OK
} else {
    obj.c.e.f; // TS Error
}

// usage with guard
validate(42, isNumber); // true
validate(42, $some(isNumber, isString)); // true
validate('42', $some(isNumber, isString)); // true
validate([], isNumber); // false

validate([1, 2, 3], isArrayOf(isNumber)); // true
validate([1, 2, 3, 'asd'], isArrayOf(isNumber)); // false

ā„¹ļø Use validateStrict to check if object has all properties from schema

Compose and create custom guard

const isOkCode = $some(is(200), is(201), is(202));

const isUserProfile = validate({
    id: isNumber,
    name: isString,
    age: $some(isNumber, isNil),
    avatarUrl: $some(isString, isNil),
});

const isSuccessResult = validate({
    ok: is(true),
    code: isOkCode,
    result: {
        id: is.Number,
        users: is.ArrayOf(isUserProfile),
    },
});

// true
isSuccessResult({
    ok: true,
    code: 200,
    result: [
        {
            id: 42,
            user: {
                id: 42,
                name: 'John',
                age: null,
                avatarUrl: null,
            },
        },
    ],
});
3.0.0-rc1

2 years ago

2.2.3

2 years ago

2.2.2

2 years ago

2.2.4

2 years ago

2.2.1

2 years ago

2.2.0

2 years ago

2.1.12

2 years ago

2.1.11

2 years ago

2.1.10

2 years ago

2.1.9

2 years ago

2.1.8

2 years ago

2.1.7

2 years ago

2.1.6

2 years ago

2.1.5

2 years ago

2.1.2

2 years ago

2.1.1

2 years ago

2.1.0

2 years ago

2.1.0-alpha1

2 years ago

2.0.6

2 years ago

2.0.4

2 years ago

2.0.3

2 years ago

2.0.2

2 years ago

2.0.0

2 years ago

2.0.0-alpha2

2 years ago

2.0.0-alpha1

2 years ago