1.4.3 ā€¢ Published 6 months ago

ts-types-guard v1.4.3

Weekly downloads
-
License
MIT
Repository
-
Last release
6 months ago

TS Types Guard

Features:

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

Guards

NameDescription
is.String(value)Check if value a string literal or string created by String constructor
is.Number(value)Check if value a number literal or number created by Number constructor
is.Boolean(value)Check if value a boolean
is.NaN(value)Check if value is a NaN value
is.Nil(value)Check if value is a null or undefined
is.Symbol(value)Check if value is a Symbol
is.RegExp(value)Check if value is a RegExp object or RegExp literal
is.Error(value)Check if value is an JS Error object
is.Primitive(value)Check if value is a primitive
is.PlainObject(value)Check if value is a plain JavaScript object
is.Array(value)Check if value is array
is.Function(value)Check if value is an any function (except class definition)
is.Class(value)Check if value is a class definition
is.Promise(value)Check if value is a promise object
is.PromiseLike(value)Check if value is a promise-like object (has then method)
is.Iterable(value)Check if value is iterable (arrays, strings, maps, sets, etc.)
is.Date(value)Check if value is a valid JS Date object
is.Empty(value)Check if value is empty
is.HasProperty(obj, propertyName)Check if an object has a property
is.ArrayOf(array, guard)Check if all elements of array match given guard
is.InstanceOf(value, constructor)Check if value is instance of given constructor

ā„¹ļø 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

Usage

import is from 'ts-guards';

const value: string | number = get();

if (is.String(value)) {
    value.toUpperCase(); // Ensures that value is string
} else {
    value.toFixed(); // Ensures that value is number
}
type Data = { prop1: number; prop2: string };

const dataOrNil = null! as Data | null | undefined;

if (!is.Nil(dataOrNil)) {
    console.log(dataOrNil.prop1); // OK
} else {
    console.log(dataOrNil.prop2); // TS Error
}

$ Utility methods

$not

Inverse given guard

const notIsNil = is.$not(is.Nil);

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

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

$some and $every

Combine multiple guards with some or every logic

const isNumberOrString = is.$some(is.Number, is.String);
const isEmptyArray = is.$every(is.Array, is.Empty);

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

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

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
import is, { validate } from 'ts-types-guard';
const value = JSON.parse('...');

// validate also supports currying
validate(value, { someProp: is.ArrayOf(is.Number) }); // valid
validate({ someProp: is.ArrayOf(is.Number) })(valid); // valid

validate addon

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

Usage

const obj = JSON.parse('...');

const schema = {
    a: is.Number,
    b: is.$some(is.String, is.Nil), // string or nil
    c: {
        d: is.Boolean,
        e: {
            f: is.Number,
            g: is.String,
        },
    },
};

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

// usage with guard
validate(42, is.Number); // true
validate(42, is.$some(is.Number, is.String)); // true
validate('42', is.$some(is.Number, is.String)); // true
validate([], is.Number); // false

validate([1, 2, 3], is.ArrayOf(is.Number)); // true
validate([1, 2, 3, 'asd'], is.ArrayOf(is.Number)); // false

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

Compose and create custom guard

import is, { validate } from 'ts-types-guard';

function isExact<T>(expected: T) {
    return (value: unknown): value is T => Object.is(value, expected);
}

const isUserProfile = validate({
    id: is.Number,
    name: is.String,
    age: is.$some(is.Number, is.Nil),
    avatarUrl: is.$some(is.String, is.Nil),
});

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

// true
isSuccessResult({
    ok: true,
    result: [
        {
            id: 42,
            user: {
                id: 42,
                name: 'John',
                age: null,
                avatarUrl: null,
            },
        },
    ],
});
1.3.7

6 months ago

1.3.6

6 months ago

1.3.5

6 months ago

1.4.3

6 months ago

1.3.4

6 months ago

1.4.2

6 months ago

1.3.3

6 months ago

1.2.4

6 months ago

1.4.1

6 months ago

1.3.2

6 months ago

1.2.3

6 months ago

1.4.0

6 months ago

1.3.1

6 months ago

1.2.3-0

6 months ago

1.2.2

6 months ago

1.2.1

6 months ago

1.1.3

6 months ago

1.1.2

6 months ago

1.1.1

6 months ago

1.1.0

6 months ago

1.0.9

6 months ago

1.0.8

6 months ago

1.0.7

6 months ago

1.0.6

6 months ago

1.0.5

6 months ago

1.0.5-0

6 months ago

1.0.4

6 months ago

1.0.4-0

6 months ago