typescript 打字稿如何判断该元素是复选框,所以 element.checked 不是红色下划线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33242324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:06:58  来源:igfitidea点击:

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

checkboxtypescript

提问by Petr Kr?márik

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 simply do

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

element: HTMLElement
if (element.InputType.toLowerCase() == "checkbox"){
    element.checked = true;
}

than it is working, but element.checked is red underlined. I think that I simply have to retype from HTMLElement to something like CheckboxElement, but did not find anything suitable for this conversion. How to get rid of this ? I have facing this also in case of element.value

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

采纳答案by PSL

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

没有“复选框”元素类型,因为它只是一个带有 type 的“输入”元素checkbox。您可以使用/断言类型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;
}

回答by Martin Vseticka

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

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;