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 oftype
andunveil
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 =// revealing the prototype of the inputconst x = '[1, 2, 3]'snitchtypex // 'String'// trying to convert the input with unveilconst y = snitchsnitchtypey // 'Array'
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 // { a: 1, "1": "b" } // you can do thissnitch// returns: { '1': 'b', a: 1, c: [ 1, 2, 3 ] } // but, you can't do this at the momentsnitch// returns: '{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 = const x = 1 2 3const y = '[1,2,3]' === // false === // true // or use the combination === // true const z = "hello, world"// true
More Examples
snitchtype1 true // 'Integer'snitchtype1 false // 'Number'snitchtype11 // 'Float'snitchtypeNumberNan // 'NaN'snitchtype1 / 'a' // 'NaN'snitchtype1 / 'a' false // 'Number'snitchtype1 / 0 // 'Infinity'snitchtype-1 / 0 // '-Infinity'snitchtype'hello world' // 'String'snitchtype1 2 3 // 'Array'snitchtype a: 1 b: 2 // 'Object'...
Modules
convert
: Convert data tostrings
,numbers
,arrays
, orobjects
snitchconvert// '1' snitchconvert// 1 snitchconvert// ['hello', 'world'] const x = a: 1 b: 2 snitchconvert // [1, 2] snitchconvert// ['a', 'b'] snitchconvert// {'0': 'a', '1': 'b'}
detect
: Helper functions for single type detection
snitchdetect // truesnitchdetect // truesnitchdetect // truesnitchdetect // falsesnitchdetect // truesnitchdetect // false...