3

I have the following event in onSubmit using React and I am changing it from Javascript to TypeScript.

const submitUserHandler = (e) => {

e.preventDefault();
dispatch(
  authenticate({
    name: e.target.personname.value,
    pw: e.target.password.value,
  })
);
};

I have tried assigning 'e: React.ChangeEvent' to the event, but it prompts an error like this:

Property 'personname' does not exist on type 'EventTarget & HTMLInputElement'.

How could I specify the type also including personname and password? Thanks!

2
  • 1
    e.target will equal to your HTMLInput Element I believe. Need to see your HTML, why there is property of "personname" in the element Commented Jan 23, 2021 at 15:27
  • typescript does not support inside event yet. You can use to pass this case: (e.target as any).personname.value Commented Jan 23, 2021 at 16:40

1 Answer 1

7

You can do something like this

<form
  ref={formRef}
  onSubmit={(e: React.SyntheticEvent) => {
    e.preventDefault();
    const target = e.target as typeof e.target & {
      personname: { value: string };
      password: { value: string };
    };
    const email = target.personname.value; // typechecks!
    const password = target.password.value; // typechecks!
    // etc...
  }}
>
  <div>
    <label>
      Email:
      <input type="personname" name="personname" />
    </label>
  </div>
  <div>
    <label>
      Password:
      <input type="password" name="password" />
    </label>
  </div>
  <div>
    <input type="submit" value="Log in" />
  </div>
</form>

For details, reference

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.