Tuesday, January 3, 2017

Extended `typeof` in JavaScript


For a long time I have looked better `typeof` functionality in JavaScript. A function that would provide a more real-world answer for any JavaScript variable. Back in November I found Axis written by Todd Motto. At first glance it looked like it would fit my need.

Axis is great. It is less than 1K in size and simple to use. You just call `axis.isString('')` or `axis.isArray([])`. Todd provided `is` functions for all of the ES5 variable types. But after playing with Axis for a few minutes before I found a few bugs and realized that it didn't support ES6 types and I wanted, among other things, to know the type of a variable so I could use it in a switch statement. I liked what Todd had created but I wanted more.

So I created `xto` (Which stands for eXtended TypeOf). It does everything that Axis does but it fixed the few bugs related to `null` and `undefined` and added the features I needed.

With `xto` you can call `xto.isAtring(v)`, `xto.isMap(v)`, `xto.isPromise(v)`, etc. But you can also call `xto.typeof(v)` to get back the type of variable `v`. If you want to know the instance of an object you can call `xto.instance(v)` and if you want to know the entire instance hierarchy you can call `xto.instances(v)` which will return an array of instance strings.

I also added `xto.isAnyArray(v)` and `xto.isTypedArray(v)`. `xto.isAnyArray(v)` returns true if `v` is an `Array`, `Int16Array`, `Float64Array` or any other ES6 typed array. `xto.isTypedArray(v)` returns true is `v` is one of the ES6 typed arrays like `Int8Array`, `UInt32Array`, etc.

`xto` was written to use anywhere. You can `require` it in your Node.js code, `Import` it into Client-side JavaScript or just load it through a `<script>` tag. The minimized file is less than 2K in size. I have hand optimized the code to produce the smallest file possible.

If you need a better way to tell the typeof a JavaScript variable or the instance of a JavaScript object then `xto` is here to help.