6
votes

It seems pretty simple but I can't handle this problem I always get same message in console:

Type error: Type '(event: MouseEvent) => void' is not assignable to type '() => Event'. TS2322

This is my code:

//in one class  
//some code 
render() 
    return (
        <div className={keyStyle} key={key} onClick={() => this.props.turnKey()}></div>
    )

//in other classs
//some code
    return (
       <div className="container">
          <Display />
          <Keys turnKey={this.activateKey}/>
       </div>
    );
  }

  activateKey = (event : React.MouseEvent): void =>{
      console.log(event.target);
  }

How do I solve this error?

2
Could you clarify which component is including which component?Aron

2 Answers

8
votes

You did not pass event (which is necessary) to your this.props.turnKey. I recommend you to pass this.props.turnKey as is:

<div className={keyStyle} key={key} onClick={this.props.turnKey}>

Probably, it should solve your problem.


If not, then there is some problem with declaration of the prop this.props.turnKey. Possibly, you have declared it like this

turnKey: () => Event

instead of

turnKey: (event: React.MouseEvent) => void
0
votes

About the problem with event.target : TS2532: Object is possibly 'undefined'.

You could declare the target as HTMLDivElement. Thus

  activateKey = (event : React.MouseEvent): void =>{
    const clickedElement = event.target as HTMLDivElement;
    console.log(clickedElement.value); // ot whatever you need
  }

should do the trick.