DEV Community

Discussion on: Javascript types?

Collapse
 
aminnairi profile image
Amin

Hi there, thanks for your article and very cool to see some multi-lingual and short articles like yours!

Just for fun, here is a little utility function I use for going a little deeper with the example you gave with Object.prototype.toString.call.

"use strict";

const type = target => Object.prototype.toString.call(target).match(/\[object (?<type>.*)\]/).groups.type;

console.log(type(""));                  // String
console.log(type(0));                   // Number
console.log(type(false));               // Boolean
console.log(type([]));                  // Array
console.log(type({}));                  // Object
console.log(type(Symbol("")));          // Symbol
console.log(type(() => {}));            // Function
console.log(type(async () => {}));      // AsyncFunction
console.log(type(Promise.resolve()));   // Promise

And you can make this function work on your own class by using Symbol.toStringTag.

class Just {
    constructor(value) {
        this.value = value;
    }
}

console.log(type(new Just(0))); // Object

class Nothing {
    get [Symbol.toStringTag]() {
        return "Nothing";
    }
}

console.log(type(new Nothing())); // "Nothing"