I'm trying to get the correct type for this function parameter
const handleInputChange = ({ target }) => {
setFormValues({
...formValues,
[target.name]: target.value,
});
};
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
its throwing me an error that didn't crash the app but I know its not a good practice.
to give more context, all the fields that are changing are strings.
CodePudding user response:
It's telling you that because you haven't told it what the type of the parameter is.
You need to tell it what the type is. There are a couple of ways:
Type the constant you're assigning the function to; or
Directly type the parameter
Type the constant you're assigning the function to
You can do that with the ChangeEventHandler
type, which is generic, taking the type of the element as a type argument:
import { ChangeEventHandler } from "react";
// ...
const onChange: ChangeEventHandler<HTMLInputElement> = ({currentTarget}) => {
// type −−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
console.log(`${currentTarget.name} => ${currentTarget.value}`);
};
Directly type the parameter
The parameter is an event object which has a currentTarget
property, so if (for instance) this is being used on an HTMLInputElement
, you can use the type { currentTarget: HTMLInputElement }
:
const handleInputChange = ({ currentTarget }: { currentTarget: HTMLInputElement }) => {
// type −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ...
};
Or you can use ChangeEvent<T>
:
import { ChangeEvent } from "react";
// ...
const handleInputChange = ({ currentTarget }: ChangeEvent<HTMLInputElement>) => {
// type −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// ...
};
Note I used currentTarget
rather than target
. It doesn't usually matter for input
elements (target
and currentTarget
are always be the same if the handler is on the input
, not its parent/ancestor), but it does for button
elements and some others (since target
might be a descendant element). And it matters if you're handling change
on a parent/ancestor element instead of on the input
directly.