Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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
like image 688
rlegendi Avatar asked Aug 01 '26 21:08

rlegendi


1 Answers

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
like image 94
Joshua Opata Avatar answered Aug 04 '26 14:08

Joshua Opata



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!