Categories
TypeScript Answers

How to set event object TypeScript types with React?

Spread the love

Sometimes, we want to set event object TypeScript types with React.

In this article, we’ll look at how to set event object TypeScript types with React.

How to set event object TypeScript types with React?

To set event object TypeScript types with React, we can use React.FormEvent<EventTarget> for the event object’s type.

For instance, we write

const App = () => {
  //...
  const update = (e: React.FormEvent<EventTarget>): void => {
    const target = e.target as HTMLInputElement;
    //...
  };
  //...
};

to set the event object e‘s type to React.FormEvent<EventTarget>.

And then we cast e.target‘s type to HTMLInputElement if we know the event is triggered from an input element.

Conclusion

To set event object TypeScript types with React, we can use React.FormEvent<EventTarget> for the event object’s type.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *