Blog
Lessons from open-source: typeof alternative to get a variable type

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)

![](https://cdn-images-1.medium.com/max/1000/1*VW-6XB0rXTGJ6gap_EK_rQ.png align="left")

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.

About me:

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.

I am open to work on interesting projects. Send me an email at ramu.narasinga@gmail.com

My Github —  https://github.com/ramu-narasinga

My website —  https://ramunarasinga.com

My Youtube channel —  https://www.youtube.com/@ramu-narasinga

Learning platform —  https://thinkthroo.com

Codebase Architecture —  https://app.thinkthroo.com/architecture

Best practices —  https://app.thinkthroo.com/best-practices

Production-grade projects —  https://app.thinkthroo.com/production-grade-projects

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 ;)

We use cookies
We use cookies to ensure you get the best experience on our website. For more information on how we use cookies, please see our cookie policy.

By clicking "Accept", you agree to our use of cookies.

Learn more