我正在检查TS中某些元素的输入类型,fe复选框。现在我确定我的元素是复选框,所以这个元素应该检查属性。但如果我只是做
element: HTMLElement
if (element.InputType.toLowerCase() == "checkbox"){
element.checked = true;
}
比它工作,但是element.checked是红色下划线。我认为我只需要从HTMLElement重新输入类似CheckboxElement的内容,但没有找到任何适合此转换的内容。如何摆脱这个?在element.value
的情况下,我也面临这种情况答案 0 :(得分:5)
没有"复选框"元素类型,因为它只是一个"输入"类型为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;
}
答案 1 :(得分:5)
其他人已经说过,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;