javascriptangularjstypescriptdom

How to use document.getElementById() method in TypeScript?


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?


Solution

  • 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()