Typescript how to tell that element is checkbox, so element.checked is not red underlined

前端 未结 2 1113
旧时难觅i
旧时难觅i 2020-12-20 16:50

I am checking for input type of some element, fe checkbox in TS. Now I am sure that I have element that is checkbox, so this element should have property checked. But if I s

相关标签:
2条回答
  • 2020-12-20 17:33

    There is no "checkbox" element type as it is just an "input" element with type checkbox. You could use/assert with the type HTMLInputElement which is an extension of HTMLElement:

    var element: HTMLInputElement;
    //... You still need to do all the null checks as necessary
    //The below check may be irrelevant depending upon what you are actually doing. 
    //But i am just adding here to show that you need to refer to the property "type" and 
    //not "InputType"
    if (element.type.toLowerCase() == "checkbox") { 
         element.checked = true;
    }
    
    0 讨论(0)
  • 2020-12-20 17:37

    The if statement is not necessary as others have already stated. However, there are several ways how to make compiler happy:

    // 1st (best variant in my opinion)
    let e1: HTMLInputElement; // type of variable
    e1.checked = true;
    
    // 2nd (sometimes a good option too)    
    let e2 = document.getElementById('myInput');
    (<HTMLInputElement>e2).checked = true; // "hint" the type to TypeScript
    
    // 3rd (a hack that may come handy sometimes)
    let e3 = document.getElementById('myInput');
    e2['checked'] = true;
    
    0 讨论(0)
提交回复
热议问题