Home > Software engineering >  getting error on form onSubmit because of wrong type in react typescript
getting error on form onSubmit because of wrong type in react typescript

Time:06-06

I have the below function and when I pass the function into another component I need to define the type of updateChannelInfo but my type is showing wrong,

const updateChannelInfo = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    updateTitle(channelTitle);
    selectedGame && updateChannelGame(selectedGame);
  };

I am getting error on onSubmit

interface EditChannelInfo {
  updateChannelInfo: React.FormEvent<HTMLFormElement>;
}

const EditChannelInfoCollapse = (props: EditChannelInfo): ReactElement => {
 <form onSubmit={updateChannelInfo}>
 ...
 </form>

}

Error:

(property) DOMAttributes<HTMLFormElement>.onSubmit?: React.FormEventHandler<HTMLFormElement> | undefined
Type 'FormEvent<HTMLFormElement>' is not assignable to type 'FormEventHandler<HTMLFormElement>'.
  Type 'FormEvent<HTMLFormElement>' provides no match for the signature '(event: FormEvent<HTMLFormElement>): void'.ts(2322)
index.d.ts(1384, 9): The expected type comes from property 'onSubmit' which is declared here on type 'DetailedHTMLProps<FormHTMLAttributes<HTMLFormElement>, HTMLFormElement>'

CodePudding user response:

This

interface EditChannelInfo {
  updateChannelInfo: React.FormEvent<HTMLFormElement>;
}

should be

interface EditChannelInfo {
  updateChannelInfo: (event: React.FormEvent<HTMLFormElement>) => void;
}

CodePudding user response:

As an alternative answer to the existing one from Ioannis, you can skip having to declare the shape of the function and opt to use the handler type instead:

interface EditChannelInfo {
  updateChannelInfo: React.FormEventHandler<HTMLFormElement>;
}
  • Related