Home > Net >  Forbidden non-null assertion lint error for document.getElementById()
Forbidden non-null assertion lint error for document.getElementById()

Time:01-31

I am using TypeScript, and I have the following definition:

const contentElement = document.getElementById("contentId")!;

Where I know for sure the relevant element is defined in the HTML file with contendId.

I have ran eslint, and I get the following error:

Forbidden non-null assertion.

So... What would be the proper way to handle this case? Tending to simply add a suppress warning, as the other options would simply just increase complexity. But maybe I am overlooking a simple solution here, other than adding:

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion

CodePudding user response:

Forbidden non-null assertion. is just a lint warning/error because your value can be nullable. If you are sure of the value then you can cast it to the expected type like below

const contentElement = document.getElementById("contentId") as HTMLElement
  • Related