DEV Community

Cover image for Lessons from open-source: typeof alternative to get a variable type
Ramu Narasinga
Ramu Narasinga

Posted on • Updated on

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.

experiment image

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.

function

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:

functioncall

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.

function call

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

Learn the best practices used in open source.

Top comments (0)