Have you ever had the problem that you wanted to check types in JavaScript, but the typeof function of Vanilla JS gave you unreliable results?

If you don’t know what I mean, then take a look at this mess

typeof(new Date())                     // objecttypeof([‘Max’, ‘Carl’, ‘Tom’])         // objecttypeof({ name: ‘Max’, age: 20 })       // objecttypeof(/ab+c/i)                        // objecttypeof(new Error(‘Error’))             // object

But with xtype.js, there is a solution for this:
You can install it via NPM to use it with E.g. React or Node.js

npm install xtype

Or use it in the browser when you downloaded it.
But first, let’s have a look on how we can solve our mess with it:

xtype.type(new Date())                 // datextype.type([‘Max’, ‘Carl’, ‘Tom’])     // arrayxtype.type({ name: ‘Max’, age: 20 })   // objectxtype.type(/ab+c/i)                    // regexpxtype.type(new Error(‘Error’))         // error

Cool, hm? And it gets better. Because by not using the type function, but passing the value directly, we can also get more details about our value.

xtype.type(-1.1)                       // number// more details please:xtype(-1.1)                            // negative_floatxtype(1)                               // positive_integerxtype('')                              // empty_string xtype('  ')                            // whitespacextype(["Max", "Carl"])                 // multi_elem_arrayxtype(["Max"])                         // single_elem_array

Isn’t that absolutely amazing?

And it’s only 3kB in size. And it works in the Browser and with Node.js 🙂
Tip: There is so much more to discover in the 
official documentation.


0 commenti

Lascia un commento

Segnaposto per l'avatar