What type to give flow annotations for onChange etc

Viewed 6029

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.

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

For React Native:

import { type SyntheticEvent } from "react-native/Libraries/Types/CoreEventTypes";
type TextInputEvent = SyntheticEvent<{ value: string }>;

Than you can just use it: onChange: (TextInputEvent) =>

onChange event might look like this (notice using currentTarget instead of target):

onChange = (e: SyntheticInputEvent<HTMLInputElement>): void => {
    this.setState({ value: e.currentTarget.value });
}
Related