Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am trying to reset HTML Form in order to clear all the values in the input fields using;
document.getElementById('myForm').reset();
But I can use that in typescript, it's giving me an error saying document.getElementById('myForm') may be null
How can I solve this issue?
–
–
–
–
Typescript will force you to check the value is not null if you use the strictNullChecks
option (or strict
which includes strictNullChecks
). You can either perform the test or use a not null assertion (!). Also you will need to use a type assertion to assert the html element is an HTMLFormElement
as by default it will be just an HtmlElement
and reset
is present only HTMLFormElement
Just an assertion Assertion:
(document.getElementById('myForm') as HTMLFormElement).reset();
Assertion with check (recommended):
let form = document.getElementById('myForm')
if(form) (form as HTMLFormElement).reset();
Not null assertion (if you want to access just HtmlElement
member):
document.getElementById('myForm')!.click()
–
–
There are different fixes for this. You can edit your tsconfig.json and add
"strictNullChecks": false
to it. This will disable the strict null checks.
If you are absolutely sure that the element exists, you could also use !
to tell typescript that your id will always be there
document.getElementById('myForm')!.reset();
Or if you want to make sure to never get an error because the element indeed doesn't exist, check for its existance
const el = document.getElementById('myForm');
if (el) el.reset();
–
Try a check on the element. Something like:
var myForm = document.getElementById('myForm');
if(myForm) myForm.reset();
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.