9

I receive this error

Error:(17, 35) TS2339: Property 'checked' does not exist on type 'EventTarget & Element'.

But that's definitely impossible error because React docs says checked does exist on target of checkbox (https://reactjs.org/docs/forms.html#handling-multiple-inputs)

enter image description here

Here is my code. What's wrong with it so TS blows up?

// 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>
    )
  }

Alternative error message:

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

borracciaBlu
  • 4,017
  • 3
  • 33
  • 41
Green
  • 28,742
  • 61
  • 158
  • 247

3 Answers3

19

Here is a fix. You have to specify type of the element of 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>
    )
  }

Green
  • 28,742
  • 61
  • 158
  • 247
4

Check out this, I currently apply this way to my project.

  onToggle = (ev: React.ChangeEvent<HTMLInputElement>) => {
    console.log('[ev]', (ev.target as HTMLInputElement).checked);
  }

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

Btw, I think you should try useState for getting/setting the state of the checked value. For example:

const [checked, setChecked] = useState(false)

const onToggle = (ev: React.ChangeEvent<HTMLInputElement>) => {
        setChecked((ev.target as HTMLInputElement).checked);
    };

...

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

Phu Le Ngo
  • 61
  • 3
-1

You can just tell it is an any type - write (event: any). Works everywhere (in functions, the onClick attribute etc...).

elano7
  • 1,584
  • 1
  • 18
  • 18