EN VI

Why does TypeScript assume that the document object is always available?

2024-03-16 02:00:11
Why does TypeScript assume that the document object is always available?

I have the following line of code in a function:

if (!document) return;

For some reason, I am getting the following ESLint error from the official TypeScript rules:

Unnecessary conditional, value is always falsy. eslint(@typescript-eslint/no-unnecessary-condition)

It is not true that document is always truthy. When the code runs on the server, in a Node.js program or as part of a react server component, the document object is not available.

Is there a way to get TypeScript to understand that document may be undefined?

EDIT:

I intend for the code to be able to run in both a node.js (server) environment, and a browser environment. Therefore, env in eslint config is set to { node: true, browser: true, } and lib.dom.d.ts is included via this tsconfig: "lib": ["ESNext", "DOM", "DOM.Iterable"],

Solution:

Is there a way to get TypeScript to understand that document may be undefined?

This is the wrong question to ask. When running under Node.js, document is not undefined! Rather, document doesn't exist, and the statement if (!document) return; will throw ReferenceError: document is not defined. You need to use a typeof check instead:

if (typeof document === 'undefined') return;

You do not want to tell TypeScript that document has the type Document | undefined (meaning that the document variable exists but may have the value undefined). This type would allow the erroneous code if (!document) return; to compile successfully, only to crash at run time.

I'm not aware of a TypeScript language feature where you can declare that a global variable conditionally exists and thus requires typeof checks.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login