Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading