An Interest In:
Web News this Week
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
May 23, 2021 01:49 pm GMT
Original Link: https://dev.to/siddharthshyniben/a-better-typeof-4kpc
A better `typeof`
The typeof
operator is a really useful one but it has a few pitfalls:
typeof ["an", "array"] // objecttypeof /regex/g // objecttypeof null // objecttypeof NaN // numbertypeof Number('I am not a number!') // number
Ok, that's a lot of pitfalls;
But there is a way to get more detailed types using Object.prototype.toString.call()
on a value:
// This statement basically means: "Call the toString method of the object prototype on whatever value you like"Object.prototype.toString.call({ object: "true" }) // the infamous [object Object]Object.prototype.toString.call(["an", "array"]) // [object Array]Object.prototype.toString.call("a string") // [object String]Object.prototype.toString.call(1n) // [object Bigint]Object.prototype.toString.call(new Date()) // [object Date] reallyObject.prototype.toString.call(new Error("an error")) // [object Error]Object.prototype.toString.call(function () {}) // [object Function]Object.prototype.toString.call(function* () {}) // [object GeneratorFunction]Object.prototype.toString.call(/regex/gi) // [object RegExp]Object.prototype.toString.call(Symbol()) // [object Symbol]Object.prototype.toString.call(NaN) // it's not perfect: [object Number]
Of course, this could be made a function (with a few finishing touches from here)
function type(obj, showFullClass) { // Whether to return the whole type if (showFullClass && typeof obj === "object") { return Object.prototype.toString.call(obj); } if (obj == null) { return (obj + '').toLowerCase(); } // implicit toString() conversion if (isNaN(+obj)) return "nan"; var deepType = Object.prototype.toString.call(obj).slice(8,-1).toLowerCase(); if (deepType === 'generatorfunction') { return 'function' } // Prevent overspecificity (for example, [object HTMLDivElement], etc). // Account for functionish Regexp (Android <=2.3), functionish <object> element (Chrome <=57, Firefox <=52), etc. // String.prototype.match is universally supported. return deepType.match(/^(array|bigint|date|error|function|generator|regexp|symbol)$/) ? deepType : (typeof obj === 'object' || typeof obj === 'function') ? 'object' : typeof obj; }
Original Link: https://dev.to/siddharthshyniben/a-better-typeof-4kpc
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To