Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type to give flow annotations for onChange etc

I have the following component:

import { identity } from 'lodash';

export const Input = ({
  onChange = identity
  //etc.
}: {
  onChange: Event<HTMLInputElement>,
}) => <Input onChange={onChange} />

But when I run flow I get this error:

onChange = identity,
       ^^^^^^^^^^^^^^^^^^^ default value. Expected polymorphic type instead of
onChange = identity,
       ^^^^^^^^ class type: Event

I'm confused as to where to find the definition for Event.

If I look at facebook's dom types:

I can see Event here which has a target property of type EventTarget.

But looking at the EventTarget definition, I don't see any definiton for value.

I don't see to define the synthetic event so that it has a target of type HtmlInputElement.

like image 502
dagda1 Avatar asked Jul 16 '17 18:07

dagda1


2 Answers

As TLadd said, SyntheticInputEvent is what you want for the parameter. However it requires a type argument, so you'll need to make it SyntheticInputEvent<HTMLInputElement>.

like image 159
Emily Maskin Avatar answered Dec 11 '22 13:12

Emily Maskin


I would take a look at the flow doc:

https://flow.org/en/docs/frameworks/react/#adding-types-for-react-events-a-classtoc-idtoc-adding-types-for-react-events-hreftoc-adding-types-for-react-eventsa

You'd want something like this:

class MyComponent extends React.Component {
  onChange(event: Event & { currentTarget: HTMLInputElement }) {
    // ...
  }
}
like image 38
TheTFo Avatar answered Dec 11 '22 13:12

TheTFo