2

I'm trying to create a heavily typed redux implementation.

I want to create a type ActionHandler that defines an object of redux actions.

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
}

Attempt to create generic ActionHandler type

export type ActionHandler<T, Action> = {
    [key in keyof typeof T]: Action
};

As you can see i want to build a type that is an object where the keys are the interface values and the values are an action type.

'T' only refers to a type, but is being used as a value here.

rnmalone
  • 1,020
  • 13
  • 25
  • 2
    `type ActionHandler = { [key in T]: Function };` – Aleksey L. Dec 15 '19 at 13:09
  • 2
    Possible duplicate of [How to use enum as index key type in typescript?](https://stackoverflow.com/questions/52700659/how-to-use-enum-as-index-key-type-in-typescript) – jcalz Dec 15 '19 at 18:38
  • Does this answer your question? [How to use enum as index key type in typescript?](https://stackoverflow.com/questions/52700659/how-to-use-enum-as-index-key-type-in-typescript) – Celso Wellington Dec 15 '19 at 23:34

0 Answers0