Можно ли использовать библиотеку типов безопасных действий с useContext и useReducer? - PullRequest
0 голосов
/ 15 января 2020

Мне интересно, возможно ли использовать библиотеку typesafe-actions вместе с useContext и useReducer, чтобы я мог правильно TS ввести свойство dispatch моего контекста (см. Ниже) .

У меня есть следующие [сокращенные] настройки:

// createAction is from typesafe-actions and TemplateActionTypes is my action type enum
const markClean = createAction(TemplateActionTypes.MARK_CLEAN)();

// an aggregation of action creators like the one above (some w/ arguments, some without)
const actions = {
  aBunchOfActions,
  moreActions
};

type AppActions = ActionType<typeof actions>; // ActionType is from typesafe-actions

const appReducer: Reducer<AppState, AppActions> = (
  state: AppState = ...,
  action: AppActions
): AppState => {
  ...
};

type AppContextType = {
  state: AppState; // my state tree interface
  dispatch: React.Dispatch<???>; // not sure of the right typings here
};

const AppContext = React.createContext<AppContextType>({ state: ..., dispatch: ??? });

// in a parent function component
// note that React has typings for the specified dispatch variable
const [state, dispatch] = useReducer(appReducer, myState);

// followed by the XXXContext.Provider logic...


// in child function component
const { dispatch } = useContext<AppContextType>(AppContext);
const handleMarkCleanClick = () => dispatch(markClean); // typings need to be right on my dispatcher so this is copasetic

...