Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React 15 + Typescript: React.FormEvent<T> typings are incomplete?

The onChange attribute for a textarea form wants a React.EventHandler<React.FormEvent<HTMLTextAreaElement>>.

Down the rabbit hole and we find that

interface EventHandler<E extends SyntheticEvent<any>> {
    (event: E): void;
}

type FormEventHandler<T> = EventHandler<FormEvent<T>>;

/* ... */

interface FormEvent<T> extends SyntheticEvent<T> {
}

In other words, onChange simply wants a function that takes a FormEvent and returns void, and FormEvent currently is identical to SyntheticEvent.

The problem is that SyntheticEvent<T>.target: EventTarget, and EventTarget does not define value.

I noticed that there's also currentTarget: EventTarget & T, where T is HTMLTextInputArea, and that seems to have value defined. But the form handling pages show event.target being looked at, not event.currentTarget. What's the difference? Should I follow the typings or the doc?

Edit: I answered my own question. currentTarget is the element I've bound the handler to, and target is that element that received the action which precipitated this event. I suppose I always want to read value from currentTarget, so in this case, I think the typings are leading me right and the docs are leading me wrong.

like image 250
masonk Avatar asked Oct 18 '22 21:10

masonk


1 Answers

Your edit is correct.

This is a simple issue, but the infamous currentTarget/target conundrum has unfortunately lead to an amusing edit war of React typings. The reason the React docs use target is because it makes no difference on a child element and that they value simplicity as explicated here:

https://github.com/facebook/react/pull/9279

If you need a more thorough reference to freshen things up, you can read one of my interventions on this subject:

https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11508#issuecomment-256045682

like image 173
Benoit B. Avatar answered Oct 27 '22 10:10

Benoit B.