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.

3

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.