Sometimes, we want to add TypeScript type for the input onchange event.target.value property.
In this article, we’ll look at how to add TypeScript type for the input onchange event.target.value property.
How to add TypeScript type for the input onchange event.target.value property?
To add TypeScript type for the input onchange event.target.value property, we set the type of the event
object to React.ChangeEvent<HTMLInputElement>
.
For instance, we write
const App = () => {
//...
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
//...
};
//...
};
to add the onChange
function into the App
component and set it to a function that takes the e
event object parameter.
We set e
‘s type to React.ChangeEvent<HTMLInputElement>
so that we get the correct autocomplete items and type check from the TypeScript compiler.
Conclusion
To add TypeScript type for the input onchange event.target.value property, we set the type of the event
object to React.ChangeEvent<HTMLInputElement>
.