Lessons from open-source: typeof alternative to get a variable type
Ramu Narasinga
Posted on March 26, 2024
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)
Experiments:
This is quite the alternative to check if a variable type is an object or an array. This is the first time, I am discovering this.
Practice the exercises based on documentation to become an expert in Next.js.
Now you would do some check like
if (getObjectClassLabel(value) !== '[object Object]')
Looks hacky? atleast I felt like it, but I have my assurance that this is not hacky because this is what Next.js source code has.
Conclusion:
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 ;)
Get free courses inspired by the best practices used in open source.
About me:
Website: https://ramunarasinga.com/
Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/
Github: https://github.com/Ramu-Narasinga
Email: ramu.narasinga@gmail.com
Posted on March 26, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
March 25, 2024