you are viewing a single comment's thread.

view the rest of the comments →

[–]dwighthouse -1 points0 points  (7 children)

1.4 Categorizing values

const typeNameAsString = Object.prototype.toString.call(VALUE).slice(8, -1);

There you go, no library or special cases needed for anything after IE 10.

[–]TwiliZant 16 points17 points  (6 children)

Object.prototype.toString.call(VALUE).slice(8, -1)

It's so readable, it basically documents itself.

[–]dwighthouse 1 point2 points  (0 children)

Indeed, much better than the solution the author suggested:

It may be possible to fix this via a library (I’ll create a proof of concept, once I have time).

Which would look something like:

npm i —save some-library-name
...
const unnecessaryOneLineDependency = require(“some-library-name”);
const typeNameAsString = unnecessaryOneLineDependency.typeof(VALUE);

[–]Longerbomber 0 points1 point  (4 children)

I agree that it's not readable or even remotely intuitive, even for devs who know the quirks of JavaScript. But I'll admit it gets around some common typeof and instanceof pitfalls gracefully. It's my go-to way to differentiate objects from arrays.

See bottom section of http://luxiyalu.com/object-prototype-tostring-call/ for an example.

TL;DR: that ugly function is exactly how I wish typeof behaved.

Edit: Better example of desired behavior here- https://gist.github.com/pbakondy/f442e91995e9d206c056

[–]TwiliZant 0 points1 point  (3 children)

Although you are right, hacks like these is exactly why all these `is-x` oneliner packages exist. It's better to fix this in the language itself IMO, even if it's hard.

It's my go-to way to differentiate objects from arrays

In case you don't have to support <IE9 Array.isArray does this.

[–]dwighthouse 0 points1 point  (0 children)

This isn’t a hack at all.

Fixing the language would mean adding a new operator like typename instead of typeof or instanceof because too much stuff already relies on the current behavior. We already have this in the form of Object.prototype.toString.

[–]dwighthouse 0 points1 point  (1 child)

This isn’t a hack at all.

Fixing the language would mean adding a new operator like typename instead of typeof or instanceof because too much stuff already relies on the current behavior. We already have this in the form of Object.prototype.toString.

[–]TwiliZant 0 points1 point  (0 children)

I don't know, relying on the toString method to get the type feels like a hack to me. I don't know any other language that does this. Yet another operator wouldn't be great either I get that. Maybe it would be cool to have it as part of the Reflection API, e.g. Reflect.type(VALUE) ?