2

I'm making a React + typescript project. And i have number button which looks like this:

<button className="num" type='button' value={'1'} onClick={inputHandler}>1</button>

You can notice that i also have onClick={inputHandler} on that button:

  const inputHandler = (event: any) => {
   event.preventDefault();
   setInput(prev => prev.replace('_', event.target.value));}

This handler taking a value prop of button and setting it in to the input. So i am stucked on typing event for this handler. Every type i am defining returns:

Property 'value' does not exist on type 'EventTarget'.

If i typing it as "any", obviously it working. But i need to define exact type for it. Help me please.

2 Answers 2

3

Usually I'll type the event argument as a generic Event.

Inside the function I'll make a variable that receives the actual HTML element and then cast the type using the as keyword, because the argument "event" itself is not a HTML element, it is more advisable to make a variable with the target.

  const inputHandler = (event: Event) => {
    event.preventDefault();
    const element = event.target as HTMLButtonElement;
    setInput(prev => prev.replace('_', element.value));
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Typescript was yelling at me with Event so I had to change it to MouseEvent. But your suggestion to cast event target with typescript as was just awesome. Thanks :)
2

You can use event: React.MouseEvent<HTMLButtonElement, MouseEvent> as type, like so:

const inputHandler = (
  event: React.MouseEvent<HTMLButtonElement, MouseEvent>
) => {
  event.preventDefault();
  //...
};

Edit angry-fast-upe615

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.