mirror of
https://github.com/microsoft/frontend-bootcamp.git
synced 2026-01-26 14:56:42 +08:00
battled and won typings
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
import { Reducer } from 'redux';
|
||||
import { ActionTypes, TodoAction } from '../actions';
|
||||
import { ActionTypes, TodoAction, TodoActionLookup } from '../actions';
|
||||
import { Draft, produce } from 'immer';
|
||||
|
||||
export type ImmerReducer<T> = (state: Draft<T>, action: TodoAction) => T;
|
||||
export type HandlerMap<T> = { [actionType in ActionTypes]?: ImmerReducer<T> };
|
||||
export type ImmerReducer<T, A = any> = (state: Draft<T>, action: A) => T;
|
||||
export type HandlerMap<T> = { [actionType in ActionTypes]?: ImmerReducer<T, TodoActionLookup[actionType]> };
|
||||
|
||||
function isHandlerFunction<T>(handlerOrMap: HandlerMap<T> | ImmerReducer<T>): handlerOrMap is ImmerReducer<T> {
|
||||
if (typeof handlerOrMap === 'function') {
|
||||
@@ -13,12 +13,16 @@ function isHandlerFunction<T>(handlerOrMap: HandlerMap<T> | ImmerReducer<T>): ha
|
||||
return false;
|
||||
}
|
||||
|
||||
export function createReducer<T>(initialState: T, handlerOrMap: HandlerMap<T> | ImmerReducer<T>): Reducer<T> {
|
||||
return function reducer(state = initialState, action: TodoAction): T {
|
||||
export function createReducer<T, AType extends ActionTypes | never = never>(
|
||||
initialState: T,
|
||||
handlerOrMap: HandlerMap<T> | ImmerReducer<T, TodoActionLookup[AType]>
|
||||
): Reducer<T> {
|
||||
return function reducer(state = initialState, action: TodoAction | TodoActionLookup[AType]): T {
|
||||
if (isHandlerFunction(handlerOrMap)) {
|
||||
return produce(state, draft => handlerOrMap(draft, action));
|
||||
return produce(state, draft => handlerOrMap(draft, action as TodoActionLookup[AType]));
|
||||
} else if (handlerOrMap.hasOwnProperty(action.type)) {
|
||||
return produce(state, draft => handlerOrMap[action.type](draft, action));
|
||||
const handler = handlerOrMap[action.type] as ImmerReducer<T>;
|
||||
return produce(state, draft => handler(draft, action));
|
||||
} else {
|
||||
return state;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user