0

I liked the approach taught at https://www.pluralsight.com/guides/handling-multiple-inputs-with-single-onchange-handler-react but I'm having trouble converting it to TypeScript.

See the red-underline errors (such as Property 'checked' does not exist on type 'EventTarget & (HTMLTextAreaElement | HTMLInputElement)'.):

enter image description here

  function handleChange(event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) {
    const thisField = event.target.name;
    const value = event.target.type === 'checkbox' ? event.target.checked : event.target.value;
    console.log(thisField, value);
    setUser({
      ...user,
      [thisField]: value,
    });
  }

What do I need to change about my types to resolve these errors?

1 Answer 1

1

Use the Typescript 'as' keyword to narrow down the type of the event object.

const value = event.target.type === 'checkbox' ? (event as React.ChangeEvent<HTMLInputElement>).target.checked : event.target.value;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.