Lessons from open-source: typeof alternative to get a variable type
This lesson is picked from Next.js source code. In this article, you will learn how Next.js checks if an error is plain object and why such a check is necessary.
I was exploring is-error.ts and found isPlainObject imported at the top of the file.
How do you usually check if a variable is an object? I would just do typeof variable == “object”, but this also means when you do typeof array, it returns object. So is there a better way? yes there is.
I found this function in is-plain-object.ts. The answer you are looking for is in what is returned from the above function. Object.prototype.toString.call(value)
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.
You can call Object.prototype.toString.call(variable) to check if the variable type is an object or array because this returns [object Array] or [object Object] unlike what you see when you use typeof variable, that returns “object” for an array as well.
It seemed a bit odd for me to check for “[object Object]” in the “if” block, that is because I am used to typeof == “object”. I can now confidently add a check like “if (getObjectClassLabel(value) !== ‘[object Object]’)” because I have learnt that elite devs do it this way in the Next.js source code. It is about confidence ;)