JS&TS
April 16, 2024

Raw type in JS

There we will talk about the raw type and how to get it.

JavaScript

As you know JS has a prototype approach\system and basically the top chain's item of JS prototype system is an Object. The Object has a couple of methods like toString or valueOf into prototype.

So, as we mentioned before the Object it's the root of prototype's chain and and that means you can call the prototype's Object methods on each built-in JS functions.

Number(10).toString(); // '10'
String('text').toString(); // 'text'
new Date().toString(); // 'Tue Apr 16 2024 22:49:42 GMT+0300'
// ...

Usually it returns string representation but if called toString onto Object's prototype it'll return the internal representation of built-in function.

Object.prototype.toString(Number()); // '[object Object]'
Object.prototype.toString(String()); // '[object Object]'
Object.prototype.toString(Boolean()); // '[object Object]'

it returns '[object Object]' because of Object is the base unit of JS code (the prototype's root chain), but if you want to see the exact (raw) type you will need to apply that method on the desired value through this mechanism.

Object.prototype.toString.call(10); // '[object Number]'
Object.prototype.toString.call('text'); // '[object String]'
Object.prototype.toString.call(false); // '[object Boolean]'

Now you can just slice the string output.

function getRawType(value: any): string => {
  return Object.prototype.toString.call(value).slice(8, -1);
};

Why is it better than typeof? It's not actually better, it really depends on what you want to get. For instanse if you want get the number or string type probably you should use typeof.

typeof 'text'; // string
typeof 10; // number

But in some cases you have to catch a specific types like RegExp, Symbol, Date and etc. In that cases it more applable to use Object.prototype way.

Object.prototype.toString.call(new Date()); // '[object Date]'
Object.prototype.toString.call(new RegExp()); // '[object RegExp]'
Object.prototype.toString.call(Symbol()); // '[object Symbol]'

Summary:

Usually we don't need to get types through Object.prototype way but in some cases (which we mentioned) it better to use that way, but generally typeof is enough.