Banging my head against the wall on this one…
given this function
const handleFormSubmitByButton = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const submitter = event.nativeEvent.submitter;
console.log(submitter?.value)
};
and markup
<form onSubmit={handleFormSubmitByButton}>
<button type="submit" name="test" value="test">Submit</button>
</form>
Why am I keep getting Property 'submitter' does not exist on type 'Event'.?
I tried to use SyntheticEvent from React like so: SyntheticEvent<HTMLFormElement, SubmitEvent>
This yields submitter being okay but then complaining about Property 'value' does not exist on type 'HTMLElement'.
As a last result, know it won’t work I did also try to type cast on the declaration of submitter. :S
TS version in project is 4.9.5
>Solution :
You need to add guard clauses:
const handleFormSubmitByButton = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!(event.nativeEvent instanceof SubmitEvent)) return;
const submitter = event.nativeEvent.submitter;
if (!(submitter instanceof HTMLInputElement)) return;
console.log(submitter.value); // ok
};