头图

The text starts here~

Overview

When event the type of the parameter is incorrect, the error "Property 'value' does not exist on type EventTarget" will be generated. To resolve the error, declare the type of ---377d5588f92cddf042da09ce3fa41be0 event as React.ChangeEvent<HTMLInputElement> . Then you can access its value through event.target.value .

property-value-does-not-exist-on-type-eventtarget.png

Here is an example to show how the error occurs.

 // App.tsx

function App() {

  // 👇️ incorrect event type
  const handleChange = (event: Event) => {
    console.log(event.target?.value);
  };

  return (
    <div>
      {/* ⛔️ Property 'value' does not exist on type 'EventTarget'. */}
      <input onChange={handleChange} type="text" id="message" />
    </div>
  );
}

export default App;

Declare the type correctly

To resolve the error, we must declare the type of the event parameter as React.ChangeEvent<HTMLInputElement> .

 // App.tsx

function App() {
  // ✅ correct event type
  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    console.log(event.target.value);
  };

  return (
    <div>
      <input onChange={handleChange} type="text" id="message" />
    </div>
  );
}

export default App;

The ChangeEvent type in React has a target attribute, which refers to the element to which the event is dispatched.

find out the type

The easiest way for you to find out the type of event is to write the event handler inline and hover over the event parameter of the function.

 // App.tsx

function App() {
  // 👇️ event is written inline
  return (
    <div>
      <input
        onChange={e => console.log(e.target.value)}
        type="text"
        id="message"
      />
    </div>
  );
}

export default App;

react-event-type-inline.png

The screenshot shows that when we hover over the e variable of the inline event handler, we get the correct type of event.

This approach works for all event handlers, once you know the correct type of the event, you can extract your handler function and declare its type correctly.

TypeScript can always infer the event type of an inline event handler because you have React's type definition files installed.

 # 👇️ with NPM
npm install --save-dev @types/react @types/react-dom

# ----------------------------------------------

# 👇️ with YARN
yarn add @types/react @types/react-dom --dev

Summarize

To fix the error at the beginning of the article, we need to correctly declare event the type of the parameter. The easiest way to find out the event type is to write the event handler inline and hover the mouse over the e variable to see the real event type.


chuck
300 声望41 粉丝