Simple JS module to check types more concisely
Check type of a variable in JavaScript is not so easy.
The builtin operators typeof
, instanceof
and other methods are not precise to report the type of a variable.
So, this module aims to check types of variables with more useful returns.
You can install truetype with Bower or NPM
bower i -S truetype
npm i -S truetype
If you are using JSPM you can install truetype from NPM:
jspm i truetype=npm:truetype
import truetype from 'truetype'
var truetype = require('truetype')
require(['truetype'], function(truetype) {
//...
})
<script src="path/to/truetype/truetype.min.js"></script>
Just call it passing your variable as argument:
let x = 'foo bar'
let type = truetype(x)
truetype
is a function that returns a custom Class Object with the following props and methods:
The var x
itself.
Returns a string with the JS builtin var type name like Object
, Array
, String
, Number
...
Returns a string with the var constructor name.
The returned value will be the same as toString
if tested var is a builtin type object, else will be the custom constructor name.
truetype(1).toString() //returns Number
truetype(1).instance() //returns Number
let Foo = x => this.x = x
let bar = new Foo(1)
truetype(bar).toString() //returns Object
truetype(bar).instance() //returns Foo
Predefined methods that check if x
type is {Type}
.
truetype({}).isObject() //returns true
truetype([]).isArray() //returns true
truetype('foo').isString() //returns true
truetype(true).isBoolean() //returns true
truetype(new Date).isDate() //returns true
truetype(1).isNumber() //returns true
truetype(1).isInt() //returns true
truetype(1).isFloat() //returns false
truetype(/\w/).isRegExp() //returns true
truetype(null).isNull() //returns true
truetype(undefined).isDefined() //returns false ;)
Check if x
type is equal type
argument and returns a Boolean.
It's possible to check predefined and custom constructor types.
truetype(1).is('String') //returns false
truetype(1).is('Number') //returns true
truetype(1).is('Int') //returns true
truetype(1).is('Float') //returns false
//Custom types
let Foo = (x) => this.x = x
let bar = new Foo(1)
truetype(bar).is('Foo') //returns true
- Write tests