【问题标题】:TypeScript: what is the correct "HTML type" for a checkbox input?TypeScript:复选框输入的正确“HTML 类型”是什么?
【发布时间】:2020-05-22 08:07:48
【问题描述】:

我在 angular2 应用程序中有一个复选框。我捕捉到它的点击事件并检查checked 属性值。

但是,在编译过程中,event.target.checked 无法识别:

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

基于这个post,我应该通知 typescript 的类型。

但是我输入的类型是什么?我没有在代码完成中找到任何与复选框相关的内容,HTMLInputElement 会抛出相同的错误。


HTML 输入

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

打字稿

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

【问题讨论】:

标签: javascript html typescript


【解决方案1】:
let test: HTMLInputElement;
console.log(test.checked);

工作得很好,我的 React 代码库中没有错误。检查你的打字稿没有崩溃!

【讨论】:

    【解决方案2】:

    但是我输入的类型是什么?

    如果您不确定复选框事件的类型,您可以使用 type as any,它可以接受任何格式的任何数据。

    在上述情况下,应该有 event.checked 而不是 event.target.checked 并且类型定义 (event: Event) => {} 应该替换为 (event: any) => {}

    【讨论】:

      猜你喜欢
      • 2019-05-10
      • 2011-12-12
      • 2016-11-22
      • 2018-03-09
      • 2021-10-22
      • 2022-10-24
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多