Itay Tur
Itay Tur

Reputation: 1679

React TS - Type '() => Promise<void>' is not assignable to type 'EventHandler<ClickEvent, boolean | void>'

I have a component, that has onClick prop.

I'm passing it an async handler, and getting the error:

Type '() => Promise' is not assignable to type 'EventHandler<ClickEvent, boolean | void>'. Type 'Promise' is not assignable to type 'boolean | void'. Type 'Promise' is not assignable to type 'void'.ts(2322)

Code

onClick={async () => {
        await item.onClick();
        menuRenderParams.closeMenu();
      }}

I tried using named handler _onClick, and specify the return type, but it didn't work.

While using the named handler I tried give the handler type like this: _onClick: EventHandler but got this error:

Generic type 'EventHandler' requires 1 type argument(s).

I look around for typescript promise handler type but didn't found anything.

Upvotes: 0

Views: 3235

Answers (1)

mohammad nowresideh
mohammad nowresideh

Reputation: 158

This is gonna work fine i think your type is incorrect.

take a look at this code:

type SomeFunc = () => Promise<string>

const func: SomeFunc = () => {
  return new Promise<string>((resolve, reject) => resolve("someinfo"));
};


<div
  onClick={async (event: MouseEvent) => {
    event.preventDefault();

    const result = await func();
    console.log(result);
  }}
></div>

it works fine please share your type here. make sure you have imported MouseEvent type from react

Upvotes: 0

Related Questions