Search code examples
typescripttypeerror

Get a "HTMLInputElement" type in TypeScript


There is a <input type="checkbox" id="mainCheckbox" />,I want to use the property checked of it.And the vscode waring Property 'checked' does not exist on type 'HTMLElement'.I know that must be type HTMLInputElement,But I can't change it,the method getElementById() is return the type HTMLElement;

var controlCheckbox= document.getElementById("mainCheckbox"),
    addBtn = document.getElementById("btn_add"),
    container = document.getElementById("observers");
ObserverSubject.extend(new ObserverSubject.Subject(), controlCheckbox);
controlCheckbox.onclick=()=>{
    this.Notify(controlCheckbox.checked);
}

enter image description here


Solution

  • Updated to 2023 typescript:

    const controlCheckbox = document.getElementById("mainCheckbox") as HTMLInputElement;
    

    ֿֿTry this simple cast:

    var controlCheckbox = <HTMLInputElement>document.getElementById("mainCheckbox")