Type Snitch: A Simple Type Sniffer for JS
Have you ever wondered why typeof []
returns 'object'
? I did, and that is why I started the development of typesnitch
. Now snitch.type([])
will return 'Array'
– isn't that something? Basically, all standard JS prototypes are supported and returned as a string
value. Furthermore, the Number
prototype is more differentiated (see examples below).
If you find any bugs or have suggestions feel free to help and fork the package.
Methods & Modules
Methods
type
: Returns the prototype of the valueunveil
: Tries to convert the value, or 'unveil' it, e.g., numbers in disguise :-)unveilType
: combination of type
and unveil
isType
: Check if a value has a specific type
Have a look at the tests for more usage information.
You can use type()
to get the prototype
of a given input value. The method has a second parameter that can be used to get a more detailed prototype. The detailed
parameter is set to true
per default.
With unveil()
a type conversion will be tried. At the moment it only works with integers, strings, objects and flat arrays that include number or string values. This will, hopefully, change in the future.
Basic Usage
const snitch = require('typesnitch')
const x = '[1, 2, 3]'
snitch.type(x)
const y = snitch.unveil(x)
snitch.type(y)
Handling Objects
Using unveil()
at objects
is tricky, and will improve in the future. Here is what you can do at the moment:
const z = '{a: 1, 1: "b"}'
snitch.unveil(z)
snitch.unveil('{a: 1, 1: "b", c: [1, 2, 3]}')
snitch.unveil('{a: 1, 1: "b", c: [1, 2, 3], d: {e: 1, f: 2}}')
Type Checking
You can use typesnitch
for type checking like so:
const { type, unveil, unveilType, isType } = require('typesnitch')
const x = [1, 2, 3]
const y = '[1,2,3]'
type(x) === type(y)
type(x) === type(unveil(y))
type(x) === unveilType(y)
const z = "hello, world"
isType(z, 'string')
More Examples
snitch.type(1, true)
snitch.type(1, false)
snitch.type(1.1)
snitch.type(Number.Nan)
snitch.type(1 / 'a')
snitch.type(1 / 'a', false)
snitch.type(1 / 0)
snitch.type(-1 / 0)
snitch.type('hello world')
snitch.type([1, 2, 3])
snitch.type({ a: 1, b: 2 })
...
Modules
convert
: Convert data to strings
, numbers
, arrays
, or objects
snitch.convert.toString(1)
snitch.convert.toNumber('1')
snitch.convert.toArray('hello; world', { delimiter: ';' })
const x = { a: 1, b: 2 }
snitch.convert.toArray(x, { objectKeys: false })
snitch.convert.toArray(x, { objectKeys: true })
snitch.convert.toObject(['a', 'b'])
detect
: Helper functions for single type detection
snitch.detect.isString('1')
snitch.detect.isNumber(1)
snitch.detect.isInteger(1)
snitch.detect.isInteger(1.1)
snitch.detect.isFloat(1.1)
snitch.detect.isFloat(1)
...