Last active
January 15, 2025 21:33
-
-
Save juliyvchirkov/6e0b5f123c341313c2d97c250f6ac3da to your computer and use it in GitHub Desktop.
javascript: identifies the exact type of an object or a primitive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns a string indicating the type of an object or a primitive | |
* Throws if invoked w/o arguments | |
* | |
* @param any An object or a primitive whose type is to be determined | |
* @return string The type of probed item | |
* | |
* Unlike native typeof operator identifies Null as is (not as Object) | |
* Delivers the exact type of an item not limited to 9 basic types Undefined, | |
* Null, Boolean, Number, BigInt, String, Function, Symbol and Object | |
* | |
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof | |
*/ | |
const itemType = (...args) => { | |
if (args.length) { | |
try { | |
return args[0].constructor.name | |
} catch (error) { | |
return Object.prototype.toString.call(args[0]).slice(8, -1) | |
} | |
} | |
throw new RangeError('An object or a primitive has been expected, got nothing') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment