Typescript如何告诉该元素是复选框,因此element.checked不是红色下划线

Pet*_*rik 7 checkbox typescript

我正在检查TS中某些元素的输入类型,fe复选框.现在我确定我的元素是复选框,所以这个元素应该检查属性.但如果我只是这样做

element: HTMLElement
if (element.InputType.toLowerCase() == "checkbox"){
    element.checked = true;
}
Run Code Online (Sandbox Code Playgroud)

比它工作,但element.checked是红色下划线.我认为我只需要从HTMLElement重新输入类似CheckboxElement的内容,但没有找到任何适合此转换的内容.如何摆脱这个?在element.value的情况下,我也面对这个问题

PSL*_*PSL 6

没有“复选框”元素类型,因为它只是具有type的“输入”元素checkbox。您可以使用/ assert为以下类型HTMLInputElement的扩展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;
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*cka 6

if声明不是必须的,因为其他人已经声明过。但是,有几种方法可以使编译器满意:

// 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;
Run Code Online (Sandbox Code Playgroud)