反应上下文存储bindAction类型

时间:2020-04-24 18:04:10

标签: typescript react-context

我正在编写一段代码,该代码使用React Context实现类似redux的存储。 我有一个函数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));

更新: 打字稿抱怨代码的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)

0 个答案:

没有答案