0

Why is this wrong?

<input
    id="url"
    type="text" className="form-control"
    value={url}
    placeholder="https://example.com"
    onChange={(e: React.FormEvent<HTMLInputElement>) => this.setState({
        url: e.target.value
    })}
/>

I'm getting: Property 'value' does not exist on type 'EventTarget'

Note: There is nothing wrong with the code e.target.value. That does return the correct value. My question is what is the proper "type" for this event, because React.FormEvent<HTMLInputElement> does not have the property event.target.value.

Kousha
  • 32,871
  • 51
  • 172
  • 296
  • that means you cannot use ``e.target.value``, should be ``e.target.somethingelse`` – Donald Wu Dec 30 '16 at 03:00
  • @DonaldWu yes I understand that. `e.target.value` does exist. That's just basic JS Event. I'm asking what the event type is – Kousha Dec 30 '16 at 04:01
  • I think you need to pass in (e,data) to the onChange function. The data parameter holds the value of your element. – Prasanna Dec 30 '16 at 05:55
  • @Prasanna, no there is nothing wrong with `event.target.value`. It holds the value alright, and works fine. It's just the IDE warning that is annoying that i'd like to fix. I want to find the "right" type for this event. – Kousha Dec 30 '16 at 07:14
  • I printed the `e.target` value but couldn't see any `value` in it. But if it works , one should not fret over small things. :D – Prasanna Dec 30 '16 at 09:41
  • I wonder why in your case React.FormEvent is generic, while in [react.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/36d40a63a05b5cb3413737fbdf7c9a2a26f211fd/react/react.d.ts) it is not. Anyway, question [why-is-event-target-not-element-in-typescript](http://stackoverflow.com/questions/28900077/why-is-event-target-not-element-in-typescript) suggest to cast `e.target` to `HTMLInputElement`. – Wolfgang Kuehn Dec 30 '16 at 20:00
  • Found the correct [react.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/types-2.0/react/index.d.ts) where `React.FormEvent` **is** generic. Looks like you can say `e.currentTarget.value` – Wolfgang Kuehn Dec 30 '16 at 20:43

2 Answers2

2

Just use e.currentTarget.value. I didn't even have to explicitly type e.

currentTarget will always be the element you bound the event to; target is what you actually clicked on. For more details see http://joequery.me/code/event-target-vs-event-currenttarget-30-seconds/.

0

Instead of e.target.value You should use (e.target as HTMLInputElement).value.

The property value is not defined in EventTarget type but defined in HTMLInputElement.

I used Angular docs as a reference.

Ahmed Rafik Ibrahim
  • 538
  • 1
  • 4
  • 16