8

When using this code I'm getting the error Property 'type' does not exist on type 'EventTarget'. The same is for checked, value and name.

Following the code I can see that FormEvent inherits from SyntheticEvent that in turn has a target: EventTarget. EventTarget does not have the properties I'm after. If I instead mark the event as any (event: any) the code works flawlessly. How can I fix this? I tried with a normal Html Input and then it worked by setting the event as React.ChangeEvent<HTMLInputElement>.

handleChange(event: React.FormEvent<React.Component<ReactBootstrap.FormControlProps, {}>>) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
        [name]: value
    });
}
...
<FormGroup controlId="Email">
    <Col componentClass={ControlLabel} sm={2}>
        Email
    </Col>
    <Col sm={10}>
        <FormControl name="email" type="email" value={this.state.email} onChange={(event) => this.handleChange(event)} placeholder="Email" />
    </Col>
</FormGroup>

Working code with Input:

handleChange(event: React.ChangeEvent<HTMLInputElement>) {
    ...
}

...

<input
name="email"
type="email"
value={this.state.email}
onChange={(event) => this.handleChange(event)} />
Ogglas
  • 62,132
  • 37
  • 328
  • 418
  • For future reference, see also https://github.com/react-bootstrap/react-bootstrap/issues/2781 – Arjan Mar 19 '19 at 11:45

1 Answers1

16

Solved it like this:

handleChange(event: React.ChangeEvent<HTMLInputElement>) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name as any;

    this.setState({
        [name]: value
    });
}

...

<FormControl name="email" type="email" value={this.state.email} onChange={(event) => this.handleChange(event as any)} placeholder="Email" />
Ogglas
  • 62,132
  • 37
  • 328
  • 418
  • What's the benefit of using fat arrow in the `onChange` event handler (i.e. `onChange={(event) => this.handleChange(event as any)}`) vs just `onChange={this.handleChange}`? – Henry Daehnke Jul 14 '17 at 21:57
  • Oops! Okay, I think I see why you can't use the second option. The event types are incompatible according to the TypeScript 2.X compiler. – Henry Daehnke Jul 14 '17 at 22:05
  • I use this because arrow functions don't have their own `this` or `arguments binding`. `this.setState` would not work otherwise. I could use bind to achieve the same thing but I think this is cleaner. https://facebook.github.io/react/docs/handling-events.html – Ogglas Jul 14 '17 at 22:08