Afsanefda
Afsanefda

Reputation: 3339

Typescript, styled-component error: TS2769: No overload matches this call. Overload 1 of 2

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;
};

Upvotes: 5

Views: 7316

Answers (1)

Peter Lehnhardt
Peter Lehnhardt

Reputation: 4995

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();
};

Upvotes: 3

Related Questions