简体   繁体   中英

TypeScript error Argument of type '(response) => void' is not assignable to parameter of type '(value: void) => void | PromiseLike<void>'

I got type this problem with the following code:

"Argument of type '(response: IResponse) => void' is not assignable to parameter of type '(value: void) => void | PromiseLike'".

And problem this the check() function.

Could you please help me? I've got really no ideas how to fix. Thanks!

 interface IResponse { isChecked: boolean; } type TResponse = IResponse; ..... function dispatchAsync<TResponsePayload>(dispatch: Dispatch, actionType: string, asyncCall: () => Promise<TResponsePayload>): any; .... check = async () => { const {actions, param} = this.props; await actions.getInfoById(param.id).then( (response: IResponse) => { this.setState({isChecked: response.isChecked}); } ); }; ..... getInfoById = async (id: string): Promise<void> => dispatchAsync<TPermission>(this.dispatch, CHECK_ACTION, async () => { return await this.service.getInfoById(id); });

To explain a little bit more, the TypeScript error tells you in another words that you cannot put a function that expects an argument in place of a function that doesn't expect any argument whatsoever. Imagine code like this:

 const myArg = (param: number) => setState(param + 5); const caller = (arg: () => void) => arg(); caller(myArg);

Here is pretty obvious the caller won't provide any arguments when calling it's argument. Therefore calling the caller with myArg will result in an error thrown inside the myArg as it won't receive the argument it expects.

In your example the getInfoById returns Promise<void> . That means the then method will not provide any argument to the provided callback. That is the root cause. You can fix it by telling the TypeScript that getInfoById actually returns something inside the promise (in this case I assume it is the IResponse type). Like so:

 getInfoById = async (id: string): Promise<IResponse> => dispatchAsync<TPermission>(this.dispatch, CHECK_ACTION, async () => { return await this.service.getInfoById(id); });

You can look at your code below:

getInfoById = async (id: string): Promise<void> =>
    dispatchAsync<TPermission>(this.dispatch, CHECK_ACTION, async () => {
        return await this.service.getInfoById(id);
});

You can change void in your Promise<void> with any or your spesific data type.

Because you can use return if you use void .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM