Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Property 'checked' does not exist on type 'EventTarget & Element'. Why it doesn't exist?

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'.

like image 968
Green Avatar asked Dec 14 '22 11:12

Green


2 Answers

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

like image 145
Green Avatar answered May 22 '23 21:05

Green


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

like image 28
Phu Le Ngo Avatar answered May 22 '23 20:05

Phu Le Ngo