README
truetype
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 exact type of a variable.
So, this module aims to check types of variables with more useful returns.
Installation
You can install truetype with NPM, Yarn, Snipacks, Unpkg CDN...
NPM
npm i -S truetype
Yarn
yarn add truetype
Snipacks
snipacks add unpkg truetype.js truetype
CDN
<script src="https://unpkg.com/truetype"></script>
Usage
ES6
import truetype from 'truetype'
CommonJS
var truetype = require('truetype')
AMD (RequireJS)
require(['truetype'], function(truetype) {
//...
})
Instance
Just call it with your variable as argument:
const x = 'foo bar', type = truetype(x)
truetype
is a function that returns a custom Class Object with the following props and methods:
truetype(x).value
The value of x
itself.
truetype(x).instance()
Returns a string with the x
constructor name like Object
, Array
, String
, Number
...
The returned value can be a builtin or custom constructor name.
truetype(1).instance() // returns Number
class Foo {
constructor(x) {
this.x = x
}
}
const bar = new Foo(1)
truetype(bar).instance() // returns Foo
truetype(x).is{Instance}()
Predefined methods that check if x
type is {Instance}
and returns a Boolean.
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(/\w/).isRegExp() // returns true
truetype(function(){}).isFunction() // returns true
There are 5 special methods to check values:
truetype(1).isInteger() // returns true
truetype(1.0).isFloat() // returns true
truetype(null).isNull() // returns true
truetype(null).isNotNull() // returns false
truetype(undefined).isDefined() // returns false
truetype(x).is(type)
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('Integer') // returns true
truetype(1).is('Float') // returns false
//Custom types
class Foo {
constructor(x) {
this.x = x
}
}
const bar = new Foo(1)
truetype(bar).is('Foo') // returns true