typescriptreferenceerror

ReferenceError: document is not defined (Typescript)


I'm getting the following error:

"ReferenceError: document is not defined"

This happens while trying to use document.getElementByID(); when using TypeScript.

How do I fix it?


Solution

  • This means the document has the potential of being undefined.

    You'll need to make a guard statement make TypeScript happy like this:

    if (document) document.getElementById();
    

    Now we can be sure that document exists before trying to call getElementById(), this prevents us from running into issue where document is undefined.