typeof is useful but has inherent issues. There are gaps between what a developer expects in terms of consistency and what typeof delivers.
Let us look at a few examples -
const i = 1;
console.log(typeof i); // number
typeof is a unary operator, and does not require brackets. If you indeed put the brackets around the input, they just group the input and nothing more.
More examples -
console.log(typeof (1 + 2)); // number
console.log(typeof ""); // string
console.log(typeof undefined); // undefined
console.log(typeof { fruit: "apple" }); // object
console.log(typeof ["apple"]); // object
console.log(typeof new Date()); // object
console.log(typeof null); // object
You may observe that -
- Null indicated as an object is downright dangerous
typeofagainst objects is justobject- this is not helpful
There are two options -
- just live with
typeoffor now. After all checking types in Javascript is not critical :). - do something else
Nothing works out and type is a do-or-die - choose Typescript.
What’s the Alternative?
Simple, really.
Object.prototype.toString.call(`variable`);
Repeating the same examples from the above code block.
console.log(Object.prototype.toString.call(1 + 2)); // [object Number]
console.log(Object.prototype.toString.call("")); // [object String]
console.log(Object.prototype.toString.call(undefined)); // [object Undefined]
console.log(Object.prototype.toString.call({ fruit: "apple" })); // [object Object]
console.log(Object.prototype.toString.call(["apple"])); // [object Array]
console.log(Object.prototype.toString.call(new Date())); // [object Date]
console.log(Object.prototype.toString.call(null)); // [object Null]
Related posts that may be of interest -