TypeScript:类型'EventTarget&Element'上不存在'checked'属性。为什么它不存在?

时间:2019-07-14 20:13:11

标签: reactjs typescript

我收到此错误

  

错误:(17,35)TS2339:类型'EventTarget&Element'上不存在'checked'属性。

但这绝对是不可能的错误,因为React文档说checked确实存在于复选框(https://reactjs.org/docs/forms.html#handling-multiple-inputs)的target

enter image description here

这是我的代码。怎么了,TS炸毁了?

// I specify a type for event. It must have `checked` property.
  onToggle = (ev: React.ChangeEvent) => {
    console.log('[ev]', ev.target.checked); // <= TS throws here
  }

  render() {
    return (
      <div>
        <input type="checkbox" name="switch" id="switch" onChange={ev => this.onToggle(ev)} checked={this.state.on}/>
      </div>
    )
  }

1 个答案:

答案 0 :(得分:3)

这是一个修复程序。您必须指定ChangeEvent

的元素类型
  onToggle = (ev: React.ChangeEvent<HTMLInputElement>) => {
  // onToggle = (ev: React.ChangeEvent) => {
    console.log('[ev]', ev.target.checked); // <= TS throws here
  }

  render() {
    return (
      <div>
        <input type="checkbox" name="switch" id="switch" onChange={ev => this.onToggle(ev)} checked={this.state.on}/>
      </div>
    )
  }