Gatlin.io Icon
Image of Austin Gatlin's face
March 28, 2022

JavaScript / TypeScript: typeof

The typeof operator returns a string indicating the type of the operand, aka, the entity being type-checked.

console.log(typeof 1)
// => "number"

This is a great way to safely check for the existence of a variable that might not exist. For example, modern JS/TS uses Server-Side Rendering (SSR). That means the window and document don't yet exist. Something like, window.onload = () => ... would cause a server-side failure, since window is not yet defined. Wrapping the call in if (window) ... does not solve the problem because the successful evaluation of the if-clause requires evaluating window, which is still undefined. This is why typeof is so useful in this scenario

if (typeof window != 'undefined') ...

One final gotcha, !!(typeof window) == !!'undefined' == true. That is, 'undefined' is a string, not an empty, falsey string, a truthy string. You need to explicitly compare again the string 'undefined' for the guard clause to succeed.