Reputation: 1345
I am fairly new to TypeScript and have just created a change handler function to take in the event as the parameter to set the value, i.e. event.target.value
. I have currently set this to any but thinking there must be a correct type for this?
This is my method which is within a functional react component:
const handleChange = (event: any) => {
setValue(event.target.value);
};
Upvotes: 1
Views: 5325
Reputation: 2365
If you use ChangeEvent
and supply the element type you are listening to, you can avoid the extra logic of checking to make sure target
or currentTarget
is null
.
Example:
const handleChange = ({
currentTarget,
}: ChangeEvent<HTMLInputElement>) => {
const { name, value } = currentTarget;
Upvotes: 1
Reputation: 470
Basic DOM Events are defined in a file called lib.dom.d.ts. Search for 'interface Event' and you'll find the typings for the definition in the DOM specification.
Here is an excerpt:
/** An event which takes place in the DOM. */
interface Event {
/**
* Returns the object to which event is dispatched (its target).
*/
readonly target: EventTarget | null;
// many, many more properties
}
As you can see, this interface will satisfy your code. But be aware that 'target' can be null so respect this in your handleChange function:
const handleChange = (event: Event) => {
const target = event.target; // Event | null
if (target === null) {
throw new Error('target can not be null');
}
// targets type is now Event
setValue(target.value); // target.value is of type EventTarget
};
Others asumed that you're using react. In this case have a look at the typings here. You'll find something called 'SyntheticEvent' which is "a cross-browser wrapper around the browser’s native event".
Excerpt:
interface BaseSyntheticEvent<E = object, C = any, T = any> {
nativeEvent: E;
currentTarget: C;
target: T;
// many more properties
}
interface SyntheticEvent<T = Element, E = Event> extends BaseSyntheticEvent<E, EventTarget & T, EventTarget> {}
Which satisfies your code as well.
Read more about React Events here.
Upvotes: 3