简体   繁体   English

TypeScript:复选框输入的正确“HTML 类型”是什么?

[英]TypeScript: what is the correct "HTML type" for a checkbox input?

I have a checkbox in angular2 application.我在 angular2 应用程序中有一个复选框。 I catch the click event on it and check the checked property value.我捕获了点击事件并检查了checked属性值。

However, during compilation, event.target.checked is not recognize:但是,在编译期间, event.target.checked无法识别:

error TS2339: Property 'checked' does not exist on type 'EventTarget'.

Based on this post , I should inform typescript of the type.基于这篇文章,我应该通知打字稿的类型。

But what is the type of my input ?但是我的输入类型是什么? I do not find anything related to checkbox in code completion and HTMLInputElement throws the same error.我在代码完成中没有找到与复选框相关的任何内容,并且HTMLInputElement会引发相同的错误。


HTML input HTML 输入

<input id="ID" formControlName="key" type="checkbox"
                    aria-label="Checkbox for following text input">

Typescript打字稿

$("#id").on('click', (event:Event) => {
  if (<WHAT SHOULD BE THERE ?>(event.target).checked) {
    $("#id").prop('checked', false);
  } else {
    $("#id").prop('checked', true);
  }
}
let test: HTMLInputElement;
console.log(test.checked);

Works just fine, no errors in my React codebase.工作得很好,我的 React 代码库中没有错误。 check that your typescript is not crashed!检查你的打字稿没有崩溃!

But what is the type of my input ?但是我的输入类型是什么?

If you are not sure about the type of checkbox event you can use type as any which can accept any data in any format.如果您不确定复选框事件的类型,您可以使用 type as any可以接受任何格式的任何数据。

In the above case instead of event.target.checked there should be event.checked and type definition (event: Event) => {} should be replaced by (event: any) => {}在上面的情况下,而不是 event.target.checked 应该有 event.checked 和类型定义 (event: Event) => {} 应该替换为 (event: any) => {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM