Home > Blockchain >  Type '(event: React.MouseEvent) => void' is not assignable to type '(e?: MouseEven
Type '(event: React.MouseEvent) => void' is not assignable to type '(e?: MouseEven

Time:09-08

I have:

<StyledPill
        size="small"
        label="See All Destinations"
        onClick={handleClick}
        data-index={0}
        featured={selectedSearchType === 0}
        leftIcon={<AllDestinationsIcon />}
      />

Where StyledPill has types:

export interface IPillProps {
  size: 'small' | 'medium';
  className?: string;
  featured?: boolean;
  label: string | ReactElement;
  disabled?: boolean;
  counter?: boolean;
  onClick?: (e?: MouseEvent) => void;
  leftIcon?: ReactElement<IconProps>;
  onClickLeftIcon?: (e?: MouseEvent) => void;
  rightIcon?: ReactElement<IconProps>;
  onClickRightIcon?: (e?: MouseEvent) => void;
  image?: ReactElement;
}

and handleClick is:

  const handleClick = useCallback((event: React.MouseEvent) => {
    console.log('shamoon1', {event}, {selectedSearchType});
    preventClickPropagation(event, false, (e) => setSelectedSearchType(Number((e.target as HTMLElement).dataset.index)))
  },
    []
  );

But this gives me a type error on the onClick:

Type '(event: React.MouseEvent) => void' is not assignable to type '(e?: MouseEvent<Element, MouseEvent> | undefined) => void'.
  Types of parameters 'event' and 'e' are incompatible.
    Type 'MouseEvent<Element, MouseEvent> | undefined' is not assignable to type 'MouseEvent<Element, MouseEvent>'.
      Type 'undefined' is not assignable to type 'MouseEvent<Element, MouseEvent>'.

CodePudding user response:

From the error it seems like your anonymous function should have a different signature:

Your anonymous fn signature (in useCallback) (event: React.MouseEvent) => void

What TypeScript is expecting: (e?: MouseEvent<Element, MouseEvent> | undefined) => void

I imagine if you update the typing to MouseEvent<Element, MouseEvent> | undefined for event then that'll mean you have to change the implementation to match.

  • Related