Я пишу фрагмент кода, который использует React Context для реализации магазина, подобного редуксу. У меня есть функция bindAction, которая получает создателя действия и функцию отправки в качестве параметров и оборачивает вызов создателя действия в переданную функцию отправки. Но у меня есть некоторые проблемы с типами.
import { Dispatch as ReactDispatch } from "react";
export interface Action<T, P> {
type: T;
payload: P;
}
export const SET_CUSTOMER_SEARCH = "SET_CUSTOMER_SEARCH";
export type SetCustomerSearchAction = Action<typeof SET_CUSTOMER_SEARCH, string>;
export interface PagerState {
currentPage: number;
pageSize: number;
totalCount: number;
}
export const SET_PAGER = "SET_PAGER";
export type SetPagerAction = Action<typeof SET_PAGER, PagerState>;
export type AppActions =
SetCustomerSearchAction
| SetPagerAction
;
export type Dispatch = ReactDispatch<AppActions>;
export function setCustomerSearch(customerSearch: string): SetCustomerSearchAction {
return {
type: SET_CUSTOMER_SEARCH,
payload: customerSearch,
};
}
export function setPager(pager: PagerState): SetPagerAction {
return {
type: SET_PAGER,
payload: pager,
};
}
export type AppActionCreators =
typeof setCustomerSearch
| typeof setPager
;
export const bindAction = <A extends (...args: any) =>
AppActions>(action: AppActionCreators, dispatch: Dispatch) =>
(...args: Parameters<A>) => dispatch(action.apply(null, args));
Обновление: Typscript жалуется на часть кода action.apply
и говорит:
(parameter) action: AppActionCreators
The 'this' context of type 'AppActionCreators' is not assignable to method's 'this' of type '(this: null, customerSearch: string) => SetCustomerSearchAction'.
Type '(pager: PagerState) => SetPagerAction' is not assignable to type '(this: null, customerSearch: string) => SetCustomerSearchAction'.
Types of parameters 'pager' and 'customerSearch' are incompatible.
Type 'string' is not assignable to type 'PagerState'.(2684)