4
votes

This is my styledComponent:

const stopPropagation = (event: Event): void => {
  event.stopPropagation();
};

<StyledComp onClick={stopPropagation}> //error occurs here
    hi StyledComp
</StyledComp>

and this is how I defined it:

export type Prop = {
  onClick: (event: Event) => void;
};

export const StyledComp = styled.div<Prop>`
  display: flex;
`;

But it returns an error like:

TS2769: No overload matches this call.   Overload 1 of 2, '(props: Pick<Pick<Pick<DetailedHTMLProps<HTMLAttributes, HTMLDivElement>, "title" | "slot" | ... 252 more ... | "is"> & { ...; } & StyledComp, "title" | ... 254 more ... | "is"> & Partial<...>, "title" | ... 254 more ... | "is"> & { ...; } & { ...; }): ReactElement<...>', gave the following error.     Type '(event: Event) => void' is not assignable to type '((event: MouseEvent<HTMLDivElement, MouseEvent>) => void) & ((event: Event) => void)'.       Type '(event: Event) => void' is not assignable to type '(event: MouseEvent<HTMLDivElement, MouseEvent>) => void'.         Types of parameters 'event' and 'event' are incompatible.           Type 'MouseEvent<HTMLDivElement, MouseEvent>' is not assignable to type 'Event'.             Types of property 'target' are incompatible.               Property 'value' is missing in type 'EventTarget' but required in type '{ value: string; }'.   Overload 2 of 2, '(props: StyledComponentPropsWithAs<"div", any, StyledComp, never>): ReactElement<StyledComponentPropsWithAs<"div", any, StyledComp, never>, string | ... 1 more ... | (new (props: any) => Component<...>)>', gave the following error.     Type '(event: Event) => void' is not assignable to type '((event: MouseEvent<HTMLDivElement, MouseEvent>) => void) & ((event: Event) => void)'.       Type '(event: Event) => void' is not assignable to type '(event: MouseEvent<HTMLDivElement, MouseEvent>) => void'.

Note: You can find styled-component&Typescript docs here!

Edit:

This is Event type:

export type Event = {
  target: {
    value: string;
  };
  stopPropagation: () => void;
  preventDefault: () => void;
};
1
I'm not sure what Event exactly is, but AFAIK there is no such a built-in static type. So if you did not define it manually, you have to use React.MouseEvent instead.SMAKSS
I defined it manually it's the same as React.MouseEvent.Afsanefda
Oh Maybe I'm wrong about Event type. let me investigate maybe it is the problemAfsanefda

1 Answers

2
votes

The important part of the error message is

Type '(event: Event) => void' is not assignable to type '(event: MouseEvent<HTMLDivElement, MouseEvent>) => void'

So the onClick property of a styled div has the type (event: MouseEvent<HTMLDivElement, MouseEvent>) => void and you want to assign a function of type (event: Event) => void to it, but this does not work, because the types are incompatible.

You should write instead:

const stopPropagation = (event: MouseEvent<HTMLDivElement, MouseEvent>): void => {
  event.stopPropagation();
};