Typy
Type checking library for JavaScript with a 'sweeter' syntax.
t('foo').isString // => true
New in version 3 🔥
Version 3.0.0 introduces BREAKING changes (for node.js CommonJS style imports only).
const t = require('typy');
const { t } = require('typy');
import t, { Schema, addCustomTypes } from 'typy';
import { t, Schema, addCustomTypes } from 'typy';
Why?
There are a hundred other type checking libraries out there. But Typy is built with three core behavioral aspects.
- No surprises. Typy will never throw, no matter what the input is.
- Object check will only look for { } rather than JavaScript's native behavior of considering everything as objects such as arrays, functions, null, etc.
- Thought Driven Development. Code should exactly mimic your thoughts on the logic rather than writing extra code just because that's how JavaScript works.
t(obj).isDefined // => true
- Custom type validation and schema validation.
Install
$ npm install --save typy
Usage
import t from 'typy';
if (t('hello').isString) {
console.log('Input is a String!')
} else {
console.log('Input is not a String!')
}
t('22').isNumber
t('22').isString
t({}).isObject
t([]).isArray
t([]).isObject
const sym = Symbol('typyIsAwesome');
t(sym).isSymbol
t(obj, 'goodKey.nestedKey').isDefined
t(obj, 'badKey.nestedKey').isDefined
t(obj, 'goodKey.nestedKey').isString
t(obj, 'badKey.nestedKey').isString
const deepObj = {
nestedKey: {
goodKey: 'hello',
superNestedKey: {}
}
};
const myObj = t(deepObj, 'nestedKey.goodKey').safeObject;
const myObj = t(deepObj, 'badKey.goodKey').safeObject;
API
t(input, optionalObjectPath)
Pass in your input to the t() method and Typy will take care of everything
t('str')
t(22)
t({foo: 'fooooo', bar: 'barooo'})
t([2, 'three', 'hey'])
const obj = {
goodKey: {
nestedKey: 'hello world'
}
}
t(obj, 'goodKey.nestedKey')
t(obj, 'badKey.nestedKey')
isDefined
Returns true if the input is defined.
const obj = {
goodKey: 'hello'
}
t(obj.goodKey).isDefined
t(obj.badKey).isDefined
isUndefined
Returns true if the input is undefined.
const obj = {
goodKey: 'hello'
}
t(obj.goodKey).isUndefined
t(obj.badKey).isUndefined
isNull
Returns true if the input is null.
const obj = {
foo: null
}
t(obj.foo).isNull
isNullOrUndefined
Returns true if the input is null or undefined.
const obj = {
foo: null
}
t(obj.foo).isNullOrUndefined
t(obj.bar).isNullOrUndefined
isBoolean
Returns true if the input is either true
or false
.
t(true).isBoolean
t(false).isBoolean
isTrue
Returns true if the input is Boolean true
.
t(true).isTrue
t(false).isTrue
isFalse
Returns true if the input is Boolean false
.
t(true).isFalse
t(false).isFalse
isTruthy
Returns true if the input is considered truthy.
In JavaScript anything other than false
, 0
, ''
, ""
, null
, undefined
and NaN
is considered truthy.
t('Typy is amazing =)').isTruthy
t({}).isTruthy
t(22).isTruthy
t([1, 'two']).isTruthy
isFalsy
Returns true if the input is considered falsy.
In JavaScript any of these values false
, 0
, ''
, ""
, null
, undefined
and NaN
are considered falsy.
t(0).isFalsy
t(null).isFalsy
t(undefined).isFalsy
t(false).isFalsy
isObject
Returns true if the input is an object.
const obj = {
foo: null
}
t(obj).isObject
t({}).isObject
Note: Only { } objects will return this as true as opposed to javascript definition of Object which includes Arrays, Functions, anything and everything related to prototype. This is an intentional behavior as we don't want arrays to return true for isObject.
isEmptyObject
Returns true if the input is an empty object, aka object without any keys.
const obj = {
foo: 'hello there',
bar: {}
}
t(obj.bar).isEmptyObject
t({}).isEmptyObject
t(obj).isEmptyObject
isString
Returns true if the input is a string.
const obj = {
foo: 'typy is awesome =)',
}
t(obj.foo).isString
t('').isString
t(22).isString
t(null).isString
isEmptyString
Returns true if the input is an empty string.
t('').isEmptyString
t('typy is so great').isEmptyString
isNumber
Returns true if the input is a number.
t(22).isNumber
t('i am a string').isNumber
t({}).isNumber
isArray
Returns true if the input is an array.
t([]).isArray
t([1, 2, 'typy']).isArray
t({}).isArray
isEmptyArray
Returns true if the input is an empty array.
t([]).isEmptyArray
t([1, 2, 'typy']).isEmptyArray
isFunction
Returns true if the input is a function.
const func = () => {};
t(func).isFunction
t({}).isFunction
isDate
Returns true if the input is a javascript's date object.
const date = new Date();
t(date).isDate
t({}).isDate
isSymbol
Returns true if the input is a javascript's Symbol.
const mySym = Symbol(123);
const anotherSymbol = Symbol('typyIsAwesome');
t(mySym).isSymbol
t(Object(anotherSymbol)).isSymbol
t({}).isSymbol
t([]).isSymbol
t(null).isSymbol
safeObject
Safely returns the value from a nested object path without throwing any error.
const deepObj = {
nestedKey: {
goodKey: 'hello',
superNestedKey: {}
}
};
const myObj = t(deepObj, 'nestedKey.goodKey').safeObject;
const myObj = t(deepObj, 'badKey.goodKey').safeObject;
const anotherDeepObj = {
nestedArray: [{
goodKey: 'hello one',
superNestedKey: {}
}, {
goodKey: 'hello two',
superNestedKey: {
superGoodKey: 'typy is great :)'
}
}]
};
const myObj = t(anotherDeepObj, 'nestedArray[1].superNestedKey.superGoodKey').safeObject;
safeObjectOrEmpty
Safely returns the value from a nested object path if the path exists
or returns an empty object if the.
const deepObj = {
nestedKey: {
goodKey: 'hello',
superNestedKey: {}
}
};
const myObj = t(deepObj, 'nestedKey.goodKey').safeObjectOrEmpty;
const myObj = t(deepObj, 'badKey.goodKey').safeObjectOrEmpty;
const anotherDeepObj = {
nestedArray: [{
goodKey: 'hello one',
superNestedKey: {}
}, {
goodKey: 'hello two',
superNestedKey: {
superGoodKey: 'typy is great :)'
}
}]
};
const myObj = t(anotherDeepObj, 'nestedArray[1].superNestedKey.superGoodKey').safeObjectOrEmpty;
safeString
Returns the string value if the input type is string or will return an empty string ''
.
const str = t('typy is safe').safeString;
const str = t(null).safeString;
const str = t(undefined).safeString;
const str = t(22).safeString;
safeNumber
Returns the number if the input type is Number or will return 0
.
const num = t(22).safeNumber;
const num = t('22').safeNumber;
const num = t(undefined).safeNumber;
const num = t(null).safeNumber;
safeBoolean
Returns the boolean if the input type is Boolean or will return false
.
const bool = t(true).safeBoolean;
const bool = t(false).safeBoolean;
const bool = t('22').safeBoolean;
const bool = t(undefined).safeBoolean;
const bool = t(22).safeBoolean;
safeFunction
Returns the function if the input type is function or will return an empty function () => {}
.
const helloFunc = () => { return 'Hello World!' }
const func = t(helloFunc).safeFunction;
const func = t('I am a string').safeFunction;
const func = t(undefined).safeFunction;
const func = t(null).safeFunction;
safeArray
Safely returns the value from a nested object path or an empty array. If the path specified exists but is not an array, returns an array containing the value of the specified path.
const deepObj = {
nestedKey: [
{
goodKey: ['hello'],
numberKey: 10,
superNestedKey: {}
},
]
};
const myObj = t(deepObj, 'nestedKey').safeArray;
const myObj = t(deepObj, 'nestedKey[0].goodKey').safeArray;
const myObj = t(deepObj, 'nestedKey[0].numberKey').safeArray;
const myObj = t(deepObj, 'nestedKey[0].superNestedKey').safeArray;
const myObj = t(deepObj, 'nestedKey[1]').safeArray;
const myObj = t(deepObj, 'badKey.goodKey').safeArray;
isValid (Schema Validation)
isValid
is used to check and validate the schema of an object. It returns true
if the schema of the object matches the schema passed or false
if the schema doesn't match.
import t, { Schema } from 'typy';
const superheroSchema = {
name: Schema.String,
age: Schema.Number,
appearances: [
{
title: Schema.String,
alias: Schema.String,
}
],
lastSeen: Schema.Date
};
const batmanObject = {
name: 'Batman',
age: 45,
isAlive: true,
appearances: [
{
title: 'The Dark Knight',
alias: 'Bruce',
}
],
lastSeen: new Date(14894561568)
};
const isSchemaValid = t(batmanObject, superheroSchema).isValid;
const simpleSchema = {
name: Schema.String,
arr: Schema.Array
};
const obj = {
name: 'Jack',
arr: [1, 2, 3]
};
const isSchemaValid = t(obj, simpleSchema).isValid;
The following Schema types are available in typy.
- Number
- String
- Array
- Boolean
- Null
- Undefined
- Function
- Date
addCustomTypes (Custom Types)
addCustomTypes
is used to pass custom validators to Typy. It can be used to validate any ipnut for custom types, like this t(input).isMyCustomType
.
You will have to add custom types only once in the project (preferabby in entry file. ex. index.js
)
Entry file (Ex. index.js
)
import t, { addCustomTypes } from 'typy';
addCustomTypes({
isPhone: (input) => (t(input).isNumber && /^\d{10}$/g.test(String(input))),
isAddress: (input) => (t(input).isString && input.toUpperCase().includes('STREET'))
});
Anywhere in the project
import t from 'typy';
const isThePhoneNumberValid = t(9892389239).isPhone;
const isThePhoneNumberValid = t('abcdefg').isPhone;
const isTheAddressValid = t('10 Downing Street').isAddress;
const isTheAddressValid = t('I like cats 🐈').isAddress;
Contributors
Thanks goes to these amazing people 🎉
License
MIT © Dinesh Pandiyan