我正在尝试创建一个重类型化的redux实现。
我想创建一个类型ActionHandler
,该类型定义一个redux操作对象。
import { ActionHandler, CustomThunkAction} from "../types/redux";
enum AuthActionTypes {
SET_USER= 'app/user/SET_USER',
LOGOUT= 'app/user/LOGOUT'
}
interface IBaseAction {
type: AuthActionTypes
}
interface ISetUserAction extends IBaseAction {
type: AuthActionTypes.SET_USER
payload: string
}
interface ILogoutAction extends IBaseAction {
type: AuthActionTypes.LOGOUT
}
type IAuthAction = ISetUserAction | ILogoutAction
export interface AuthState {
user: string
}
const INITIAL_STATE = {
user: 'foo'
};
const actionHandlers: ActionHandler<AuthActionTypes, IAuthAction> = {
[AuthActionTypes.SET_USER]: (state: AuthState, action: ISetUserAction) => ({ user: action.payload }),
[AuthActionTypes.LOGOUT]: () => ({ user: '' })
};
export default function reducer(state: AuthState = INITIAL_STATE, action: IAuthAction) {
const handler = actionHandlers[action.type];
return handler ? handler(state, action) : state
}
试图创建通用的ActionHandler类型
export type ActionHandler<T, Action> = {
[key in keyof typeof T]: Action
};
如您所见,我想构建一个对象类型,其中键是接口值,值是操作类型。
'T'仅指类型,但在此处被用作值。