Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'MouseEvent<Element, MouseEvent>' is not assignable to type 'MouseEvent<HTMLDivElement, MouseEvent>'

I am writing a react application in typescript where I am trying to handle both right click and left click.

This is my interface

interface ButtonProps {
    value: CellValue;
    state: CellState;
    row: number;
    col: number;
    onClick(rowParam: number, colParam: number) : (e: React.MouseEvent) => void;
    onContext(rowParam: number, colParam: number) : (e: React.MouseEvent) => void;
} 

Now I have declared the callback function like

const handleContextMenu = (rowParam: number, cellParam: number) => (e: React.MouseEvent<HTMLDivElement, MouseEvent>) : void => {
      e.preventDefault();
}

and finally declared my component like

<Button 
  key={`${rowIndex}*${cellIndex}`} 
  value={cell.value} 
  state={cell.state} 
  onClick={handleCellClick}
  onContext={handleContextMenu}
  row={rowIndex} 
  col={cellIndex} 
/>

But I get an error

Type '(rowParam: number, cellParam: number) => (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void' is not assignable to type '(rowParam: number, colParam: number) => (e: MouseEvent<Element, MouseEvent>) => void'.
  Type '(e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void' is not assignable to type '(e: MouseEvent<Element, MouseEvent>) => void'.
    Types of parameters 'e' and 'e' are incompatible.
      Type 'MouseEvent<Element, MouseEvent>' is not assignable to type 'MouseEvent<HTMLDivElement, MouseEvent>'.
        Type 'Element' is missing the following properties from type 'HTMLDivElement': align, accessKey, accessKeyLabel, autocapitalize, and 111 more.  TS2322

    53 |                 state={cell.state} 
    54 |                 onClick={handleCellClick}
  > 55 |                 onContext={handleContextMenu}
       |                 ^
    56 |                 row={rowIndex} 
    57 |                 col={cellIndex} 
    58 |             />

I don't know much about typescript but according to me HTMLDivElement should be of type HTMLElement right?

like image 536
Knows Not Much Avatar asked Mar 01 '20 00:03

Knows Not Much


1 Answers

Solution

Change from HTMLDivElement to Element solve your problem.

// Before
const handleContextMenu = (...) => (e: React.MouseEvent<HTMLDivElement, MouseEvent>) : void => {
  ...
}
// After
const handleContextMenu = (...) => (e: React.MouseEvent<Element, MouseEvent>) : void => {
  ...
}

Explanation

The hierarchy relationship is as below:

⌞Element
  ⌞HTMLElement
    ⌞HTMLDivElement

  • ref: Interface HTMLDivElement

The error message is showing something like:

Type 'Element' is missing the following properties from type 'HTMLDivElement': align, accessKey, accessKeyLabel, autocapitalize, and 111 more. TS2322

This is telling that there are some props that belong to Element could not be found in HTMLDivElement.

like image 108
keikai Avatar answered Oct 28 '22 11:10

keikai