75

What is the best way to cast the action parameter in a redux reducer with typescript? There will be multiple action interfaces that can occur that all extend a base interface with a property type. The extended action interfaces can have more properties that are all different between the action interfaces. Here is an example below:

interface IAction {
    type: string
}

interface IActionA extends IAction {
    a: string
}

interface IActionB extends IAction {
    b: string
}

const reducer = (action: IAction) {
    switch (action.type) {
        case 'a':
            return console.info('action a: ', action.a) // property 'a' does not exists on type IAction

        case 'b':
            return console.info('action b: ', action.b) // property 'b' does not exists on type IAction         
    }
}

The problem is that action needs to be cast as a type that has access to both IActionA and IActionB so the reducer can use both action.a and action.a without throwing an error.

I have several ideas how to work around this issue:

  1. Cast action to any.
  2. Use optional interface members.

example:

interface IAction {
    type: string
    a?: string
    b?: string
}
  1. Use different reducers for every action type.

What is the best way to organize Action/Reducers in typescript? Thank you in advance!

5
  • check this ,spin.atomicobject.com/2017/07/24/… Dec 12, 2017 at 8:41
  • 1
    Strictly speaking, from what I've read, redux runs every single reducer over every possible action. So the action type should literally be any action type. See: redux.js.org/faq/… So the proper type is AnyAction. May 28, 2019 at 2:45
  • 1
    This question was super helpful! Since I'm working with legacy code, I ended up using a combination of these solutions, and also referencing this article medium.com/@pie6k/…
    – frederj
    Sep 6, 2019 at 14:42
  • Have you figured out a solution to this problem? I have tried the Tagged Union Types from Typescript 2 but that still does not work for me.
    – Loupi
    Jul 10, 2020 at 12:17
  • I’ve changed several projects and frameworks since 2016, and unfortunately can’t remember how did I solve this problem. There are many correct and good answers here. If I could choose more than one best answer, I would select at least five on this page. Jul 10, 2020 at 12:34

23 Answers 23

70

With Typescript 2's Tagged Union Types you can do the following

interface ActionA {
    type: 'a';
    a: string
}

interface ActionB {
    type: 'b';
    b: string
}

type Action = ActionA | ActionB;

function reducer(action:Action) {
    switch (action.type) {
        case 'a':
            return console.info('action a: ', action.a) 
        case 'b':
            return console.info('action b: ', action.b)          
    }
}
1
  • 7
    This is now discouraged in the official documentation, instead it is recommended to use type predicate functions or redux-toolkit's createSlice Sep 25, 2021 at 22:21
22

I have an Action interface

export interface Action<T, P> {
    readonly type: T;
    readonly payload?: P;
}

I have a createAction function:

export function createAction<T extends string, P>(type: T, payload: P): Action<T, P> {
    return { type, payload };
}

I have an action type constant:

const IncreaseBusyCountActionType = "IncreaseBusyCount";

And I have an interface for the action (check out the cool use of typeof):

type IncreaseBusyCountAction = Action<typeof IncreaseBusyCountActionType, void>;

I have an action creator function:

function createIncreaseBusyCountAction(): IncreaseBusyCountAction {
    return createAction(IncreaseBusyCountActionType, null);
}

Now my reducer looks something like this:

type Actions = IncreaseBusyCountAction | DecreaseBusyCountAction;

function busyCount(state: number = 0, action: Actions) {
    switch (action.type) {
        case IncreaseBusyCountActionType: return reduceIncreaseBusyCountAction(state, action);
        case DecreaseBusyCountActionType: return reduceDecreaseBusyCountAction(state, action);
        default: return state;
    }
}

And I have a reducer function per action:

function reduceIncreaseBusyCountAction(state: number, action: IncreaseBusyCountAction): number {
    return state + 1;
}
2
  • Nice setup, I will follow your example. However for the action type constant I would rather use something like this: const AccountActions = {GET_CURRENT_ACCOUNT_ASYNC: "GET_CURRENT_ACCOUNT_ASYNC"}. As a matter of covenience I tend to group them in a single object. And for large apps I tend to group them by module and domain such as AccountDataActions & AccountUiActions. This way I have to do a lot less typing when importing actions. And for further convenience I keep action type constants and action creators in the same object. Mar 19, 2017 at 14:46
  • This is still a good approach, but I switched to another one, that I have also put here as an answer to this question!
    – Elmer
    Jan 6, 2018 at 15:46
16

I might be late to the dance but enum's FTW!

enum ActionTypes {
  A = 'ANYTHING_HERE_A',
  B = 'ANYTHING_HERE_B',
}

interface IActionA {
  type: ActionTypes.A;
  a: string;
}

interface IActionB {
  type: ActionTypes.B;
  b: string;
}

type IAction = IActionA | IActionB

const reducer = (action: IAction) {
  switch (action.type) {
    case ActionTypes.A:
      return console.info('action a: ', action.a)

    case ActionTypes.B:
      return console.info('action b: ', action.b)
    }
}
3
  • 2
    It's a clean way to do it
    – Azhar
    Jun 3, 2021 at 7:48
  • 1
    I'm a total beginner with redux, but I was wondering why can't we define ActionType as an object? taking into account its usage in switch, we can define it as an object because ActionTypes.A would mean the same thing, would it?
    – Prhyme
    Jul 2, 2021 at 19:19
  • I might be late to the dance but enum's FTW! enum ActionTypes { A: 'ANYTHING_HERE_A', B: 'ANYTHING_HERE_B', } should be I might be late to the dance but enum's FTW! enum ActionTypes { A = 'ANYTHING_HERE_A', B = 'ANYTHING_HERE_B', }
    – IngoP
    Oct 16, 2021 at 11:48
15

Here's a clever solution from Github user aikoven from https://github.com/reactjs/redux/issues/992#issuecomment-191152574:

type Action<TPayload> = {
    type: string;
    payload: TPayload;
}

interface IActionCreator<P> {
  type: string;
  (payload: P): Action<P>;
}

function actionCreator<P>(type: string): IActionCreator<P> {
  return Object.assign(
    (payload: P) => ({type, payload}),
    {type}
  );
}

function isType<P>(action: Action<any>,
                          actionCreator: IActionCreator<P>): action is Action<P> {
  return action.type === actionCreator.type;
}

Use actionCreator<P> to define your actions and action creators:

export const helloWorldAction = actionCreator<{foo: string}>('HELLO_WORLD');
export const otherAction = actionCreator<{a: number, b: string}>('OTHER_ACTION');

Use the user defined type guard isType<P> in the reducer:

function helloReducer(state: string[] = ['hello'], action: Action<any>): string[] {
    if (isType(action, helloWorldAction)) { // type guard
       return [...state, action.payload.foo], // action.payload is now {foo: string}
    } 
    else if(isType(action, otherAction)) {
        ...

And to dispatch an action:

dispatch(helloWorldAction({foo: 'world'})
dispatch(otherAction({a: 42, b: 'moon'}))

I recommend reading through the whole comment thread to find other options as there are several equally good solutions presented there.

13

Here is how I do it:

IAction.ts

import {Action} from 'redux';

/**
 * https://github.com/acdlite/flux-standard-action
 */
export default interface IAction<T> extends Action<string> {
    type: string;
    payload?: T;
    error?: boolean;
    meta?: any;
}

UserAction.ts

import IAction from '../IAction';
import UserModel from './models/UserModel';

export type UserActionUnion = void | UserModel;

export default class UserAction {

    public static readonly LOAD_USER: string = 'UserAction.LOAD_USER';
    public static readonly LOAD_USER_SUCCESS: string = 'UserAction.LOAD_USER_SUCCESS';

    public static loadUser(): IAction<void> {
        return {
            type: UserAction.LOAD_USER,
        };
    }

    public static loadUserSuccess(model: UserModel): IAction<UserModel> {
        return {
            payload: model,
            type: UserAction.LOAD_USER_SUCCESS,
        };
    }

}

UserReducer.ts

import UserAction, {UserActionUnion} from './UserAction';
import IUserReducerState from './IUserReducerState';
import IAction from '../IAction';
import UserModel from './models/UserModel';

export default class UserReducer {

    private static readonly _initialState: IUserReducerState = {
        currentUser: null,
        isLoadingUser: false,
    };

    public static reducer(state: IUserReducerState = UserReducer._initialState, action: IAction<UserActionUnion>): IUserReducerState {
        switch (action.type) {
            case UserAction.LOAD_USER:
                return {
                    ...state,
                    isLoadingUser: true,
                };
            case UserAction.LOAD_USER_SUCCESS:
                return {
                    ...state,
                    isLoadingUser: false,
                    currentUser: action.payload as UserModel,
                };
            default:
                return state;
        }
    }

}

IUserReducerState.ts

import UserModel from './models/UserModel';

export default interface IUserReducerState {
    readonly currentUser: UserModel;
    readonly isLoadingUser: boolean;
}

UserSaga.ts

import IAction from '../IAction';
import UserService from './UserService';
import UserAction from './UserAction';
import {put} from 'redux-saga/effects';
import UserModel from './models/UserModel';

export default class UserSaga {

    public static* loadUser(action: IAction<void> = null) {
        const userModel: UserModel = yield UserService.loadUser();

        yield put(UserAction.loadUserSuccess(userModel));
    }

}

UserService.ts

import HttpUtility from '../../utilities/HttpUtility';
import {AxiosResponse} from 'axios';
import UserModel from './models/UserModel';
import RandomUserResponseModel from './models/RandomUserResponseModel';
import environment from 'environment';

export default class UserService {

    private static _http: HttpUtility = new HttpUtility();

    public static async loadUser(): Promise<UserModel> {
        const endpoint: string = `${environment.endpointUrl.randomuser}?inc=picture,name,email,phone,id,dob`;
        const response: AxiosResponse = await UserService._http.get(endpoint);
        const randomUser = new RandomUserResponseModel(response.data);

        return randomUser.results[0];
    }

}

https://github.com/codeBelt/typescript-hapi-react-hot-loader-example

7

Two parts of the problem

Several comments above have mentioned concept/function `actionCreator´ - take a look at redux-actions package (and corresponding TypeScript definitions), that solves first part of the problem: creating action creator functions that have TypeScript type information specifying action payload type.

Second part of the problem is combining reducer functions into single reducer without boilerplate code and in a type-safe manner (as the question was asked about TypeScript).

The solution

Combine redux-actions and redux-actions-ts-reducer packages:

1) Create actionCreator functions that can be used for creating action with desired type and payload when dispatching the action:

import { createAction } from 'redux-actions';

const negate = createAction('NEGATE'); // action without payload
const add = createAction<number>('ADD'); // action with payload type `number`

2) Create reducer with initial state and reducer functions for all related actions:

import { ReducerFactory } from 'redux-actions-ts-reducer';

// type of the state - not strictly needed, you could inline it as object for initial state
class SampleState {
    count = 0;
}

// creating reducer that combines several reducer functions
const reducer = new ReducerFactory(new SampleState())
    // `state` argument and return type is inferred based on `new ReducerFactory(initialState)`.
    // Type of `action.payload` is inferred based on first argument (action creator)
    .addReducer(add, (state, action) => {
        return {
            ...state,
            count: state.count + action.payload,
        };
    })
    // no point to add `action` argument to reducer in this case, as `action.payload` type would be `void` (and effectively useless)
    .addReducer(negate, (state) => {
        return {
            ...state,
            count: state.count * -1,
        };
    })
    // chain as many reducer functions as you like with arbitrary payload types
    ...
    // Finally call this method, to create a reducer:
    .toReducer();

As You can see from the comments You don't need to write any TypeScript type annotations, but all types are inferred (so this even works with noImplicitAny TypeScript compiler option)

If You use actions from some framework that doesn't expose redux-action action creators (and You don't want to create them Yourself either) or have legacy code that uses strings constants for action types you could add reducers for them as well:

const SOME_LIB_NO_ARGS_ACTION_TYPE = '@@some-lib/NO_ARGS_ACTION_TYPE';
const SOME_LIB_STRING_ACTION_TYPE = '@@some-lib/STRING_ACTION_TYPE';

const reducer = new ReducerFactory(new SampleState())
    ...
    // when adding reducer for action using string actionType
    // You should tell what is the action payload type using generic argument (if You plan to use `action.payload`)
    .addReducer<string>(SOME_LIB_STRING_ACTION_TYPE, (state, action) => {
        return {
            ...state,
            message: action.payload,
        };
    })
    // action.payload type is `void` by default when adding reducer function using `addReducer(actionType: string, reducerFunction)`
    .addReducer(SOME_LIB_NO_ARGS_ACTION_TYPE, (state) => {
        return new SampleState();
    })
    ...
    .toReducer();

so it is easy to get started without refactoring Your codebase.

Dispatching actions

You can dispatch actions even without redux like this:

const newState = reducer(previousState, add(5));

but dispatching action with redux is simpler - use the dispatch(...) function as usual:

dispatch(add(5));
dispatch(negate());
dispatch({ // dispatching action without actionCreator
    type: SOME_LIB_STRING_ACTION_TYPE,
    payload: newMessage,
});

Confession: I'm the author of redux-actions-ts-reducer that I open-sourced today.

3
  • 1
    Thank you very much for this solution! This helps me a lot for my current project. =)
    – fraherm
    Jun 1, 2018 at 19:41
  • What about the redux combineReducers function, how can you make it accept this ts-reducer? Feb 15, 2022 at 14:17
  • @AdonisK.Kakoulidis, the .toReducer() builds a normal redux compatible reducer, so it can be used with combineReducers as any other redux compatible reducer
    – atsu85
    Feb 18, 2022 at 16:39
5

For a relatively simple reducer you could probably just use type guards:

function isA(action: IAction): action is IActionA {
  return action.type === 'a';
}

function isB(action: IAction): action is IActionB {
  return action.type === 'b';
}

function reducer(action: IAction) {
  if (isA(action)) {
    console.info('action a: ', action.a);
  } else if (isB(action)) {
    console.info('action b: ', action.b);
  }
}
1
5

I suggest using AnyAction because according to Redux FAQ, every reducer is ran on every action. This is why we end up just returning the input state if the action is not one of the types. Otherwise we would never have a default case in our switches in our reducers.

See: https://redux.js.org/faq/performance#won-t-calling-all-my-reducers-for-each-action-be-slow

So therefore it is fine to just do:

import { AnyAction } from 'redux';

function myReducer(state, action: AnyAction) {
  // ...
}
3

To get implicit typesafety without having to write interfaces for every action, you can use this approach (inspired by the returntypeof function from here: https://github.com/piotrwitek/react-redux-typescript#returntypeof-polyfill)

import { values } from 'underscore'

/**
 * action creator (declaring the return type is optional, 
 * but you can make the props readonly)
 */
export const createAction = <T extends string, P extends {}>(type: T, payload: P) => {
  return {
    type,
    payload
  } as {
    readonly type: T,
    readonly payload: P
  }
}

/**
 * Action types
 */
const ACTION_A = "ACTION_A"
const ACTION_B = "ACTION_B"

/**
 * actions
 */
const actions = {
  actionA: (count: number) => createAction(ACTION_A, { count }),
  actionB: (name: string) => createAction(ACTION_B, { name })
}

/**
 * create action type which you can use with a typeguard in the reducer
 * the actionlist variable is only needed for generation of TAction
 */
const actionList = values(actions).map(returnTypeOf)
type TAction = typeof actionList[number]

/**
 * Reducer
 */
export const reducer = (state: any, action: TAction) => {
  if ( action.type === ACTION_A ) {
    console.log(action.payload.count)
  }
  if ( action.type === ACTION_B ) {
    console.log(action.payload.name)
    console.log(action.payload.count) // compile error, because count does not exist on ACTION_B
  }
  console.log(action.payload.name) // compile error because name does not exist on every action
}
3

With Typescript v2, you can do this pretty easily using union types with type guards and Redux's own Action and Reducer types w/o needing to use additional 3rd party libs, and w/o enforcing a common shape to all actions (e.g. via payload).

This way, your actions are correctly typed in your reducer catch clauses, as is the returned state.

import {
  Action,
  Reducer,
} from 'redux';

interface IState {
  tinker: string
  toy: string
}

type IAction = ISetTinker
  | ISetToy;

const SET_TINKER = 'SET_TINKER';
const SET_TOY = 'SET_TOY';

interface ISetTinker extends Action<typeof SET_TINKER> {
  tinkerValue: string
}
const setTinker = (tinkerValue: string): ISetTinker => ({
  type: SET_TINKER, tinkerValue,
});
interface ISetToy extends Action<typeof SET_TOY> {
  toyValue: string
}
const setToy = (toyValue: string): ISetToy => ({
  type: SET_TOY, toyValue,
});

const reducer: Reducer<IState, IAction> = (
  state = { tinker: 'abc', toy: 'xyz' },
  action
) => {
  // action is IAction
  if (action.type === SET_TINKER) {
    // action is ISetTinker
    // return { ...state, tinker: action.wrong } // doesn't typecheck
    // return { ...state, tinker: false } // doesn't typecheck
    return {
      ...state,
      tinker: action.tinkerValue,
    };
  } else if (action.type === SET_TOY) {
    return {
      ...state,
      toy: action.toyValue
    };
  }

  return state;
}

Things is basically what @Sven Efftinge suggests, while additionally checking the reducer's return type.

1
  • Thanks for updating @Sven Efftinge answer to use redux types!
    – jjbskir
    Nov 8, 2018 at 15:31
2

you could do the following things

if you expect one of IActionA or IActionB only, you can limit the type at least and define your function as

const reducer = (action: (IActionA | IActionB)) => {
   ...
}

Now, the thing is, you still have to find out which type it is. You can totally add a type property but then, you have to set it somewhere, and interfaces are only overlays over object structures. You could create action classes and have the ctor set the type.

Otherwise you have to verify the object by something else. In your case you could use hasOwnProperty and depending on that, cast it to the correct type:

const reducer = (action: (IActionA | IActionB)) => {
    if(action.hasOwnProperty("a")){
        return (<IActionA>action).a;
    }

    return (<IActionB>action).b;
}

This would still work when compiled to JavaScript.

2

The solution @Jussi_K referenced is nice because it's generic.

However, I found a way that I like better, on five points:

  1. It has the action properties directly on the action object, rather than in a "payload" object -- which is shorter. (though if you prefer the "payload" prop, just uncomment the extra line in the constructor)
  2. It can be type-checked in reducers with a simple action.Is(Type), instead of the clunkier isType(action, createType).
  3. The logic's contained within a single class, instead of spread out amonst type Action<TPayload>, interface IActionCreator<P>, function actionCreator<P>(), function isType<P>().
  4. It uses simple, real classes instead of "action creators" and interfaces, which in my opinion is more readable and extensible. To create a new Action type, just do class MyAction extends Action<{myProp}> {}.
  5. It ensures consistency between the class-name and type property, by just calculating type to be the class/constructor name. This adheres to the DRY principle, unlike the other solution which has both a helloWorldAction function and a HELLO_WORLD "magic string".

Anyway, to implement this alternate setup:

First, copy this generic Action class:

class Action<Payload> {
    constructor(payload: Payload) {
        this.type = this.constructor.name;
        //this.payload = payload;
        Object.assign(this, payload);
    }
    type: string;
    payload: Payload; // stub; needed for Is() method's type-inference to work, for some reason

    Is<Payload2>(actionType: new(..._)=>Action<Payload2>): this is Payload2 {
        return this.type == actionType.name;
        //return this instanceof actionType; // alternative
    }
}

Then create your derived Action classes:

class IncreaseNumberAction extends Action<{amount: number}> {}
class DecreaseNumberAction extends Action<{amount: number}> {}

Then, to use in a reducer function:

function reducer(state, action: Action<any>) {
    if (action.Is(IncreaseNumberAction))
        return {...state, number: state.number + action.amount};
    if (action.Is(DecreaseNumberAction))
        return {...state, number: state.number - action.amount};
    return state;
}

When you want to create and dispatch an action, just do:

dispatch(new IncreaseNumberAction({amount: 10}));

As with @Jussi_K's solution, each of these steps is type-safe.

EDIT

If you want the system to be compatible with anonymous action objects (eg, from legacy code, or deserialized state), you can instead use this static function in your reducers:

function IsType<Payload>(action, actionType: new(..._)=>Action<Props>): action is Payload {
    return action.type == actionType.name;
}

And use it like so:

function reducer(state, action: Action<any>) {
    if (IsType(action, IncreaseNumberAction))
        return {...state, number: state.number + action.amount};
    if (IsType(action, DecreaseNumberAction))
        return {...state, number: state.number - action.amount};
    return state;
}

The other option is to add the Action.Is() method onto the global Object.prototype using Object.defineProperty. This is what I'm currently doing -- though most people don't like this since it pollutes the prototype.

EDIT 2

Despite the fact that it would work anyway, Redux complains that "Actions must be plain objects. Use custom middleware for async actions.".

To fix this, you can either:

  1. Remove the isPlainObject() checks in Redux.
  2. Do one of the modifications in my edit above, plus add this line to the end of the Action class's constructor: (it removes the runtime link between instance and class)
Object.setPrototypeOf(this, Object.getPrototypeOf({}));
2

There are libraries that bundle most of the code mentioned in other answers: aikoven/typescript-fsa and dphilipson/typescript-fsa-reducers.

With these libraries all your actions and reducers code is statically typed and readable:

import actionCreatorFactory from "typescript-fsa";
const actionCreator = actionCreatorFactory();

interface State {
  name: string;
  balance: number;
  isFrozen: boolean;
}

const INITIAL_STATE: State = {
  name: "Untitled",
  balance: 0,
  isFrozen: false,
};

const setName = actionCreator<string>("SET_NAME");
const addBalance = actionCreator<number>("ADD_BALANCE");
const setIsFrozen = actionCreator<boolean>("SET_IS_FROZEN");

...

import { reducerWithInitialState } from "typescript-fsa-reducers";

const reducer = reducerWithInitialState(INITIAL_STATE)
  .case(setName, (state, name) => ({ ...state, name }))
  .case(addBalance, (state, amount) => ({
    ...state,
    balance: state.balance + amount,
  }))
  .case(setIsFrozen, (state, isFrozen) => ({ ...state, isFrozen }));
1

you can define your action something like:

// src/actions/index.tsx
import * as constants from '../constants'

export interface IncrementEnthusiasm {
    type: constants.INCREMENT_ENTHUSIASM;
}

export interface DecrementEnthusiasm {
    type: constants.DECREMENT_ENTHUSIASM;
}

export type EnthusiasmAction = IncrementEnthusiasm | DecrementEnthusiasm;

export function incrementEnthusiasm(): IncrementEnthusiasm {
    return {
        type: constants.INCREMENT_ENTHUSIASM
    }
}

export function decrementEnthusiasm(): DecrementEnthusiasm {
    return {
        type: constants.DECREMENT_ENTHUSIASM
    }
}

and so, you can define your reducer like follows:

// src/reducers/index.tsx

import { EnthusiasmAction } from '../actions';
import { StoreState } from '../types/index';
import { INCREMENT_ENTHUSIASM, DECREMENT_ENTHUSIASM } from '../constants/index';

export function enthusiasm(state: StoreState, action: EnthusiasmAction): StoreState {
  switch (action.type) {
    case INCREMENT_ENTHUSIASM:
      return { ...state, enthusiasmLevel: state.enthusiasmLevel + 1 };
    case DECREMENT_ENTHUSIASM:
      return { ...state, enthusiasmLevel: Math.max(1, state.enthusiasmLevel - 1) };
  }
  return state;
}

Complete official docs: https://github.com/Microsoft/TypeScript-React-Starter#adding-a-reducer

1

If you need to fix your implementation exactly as you posted, this is the way how to fix it and get it working using type assertions , respectively as I show in the following:

interface IAction {
  type: string
}

interface IActionA extends IAction {
  a: string
}

interface IActionB extends IAction {
  b: string
}

const reducer = (action: IAction) => {
  switch (action.type) {
      case 'a':
          return console.info('action a: ', (<IActionA>action).a) // property 'a' exists because you're using type assertion <IActionA>

      case 'b':
          return console.info('action b: ', (<IActionB>action).b) // property 'b' exists because you're using type assertion <IActionB>
  }
}

You can learn more on section "Type Guards and Differentiating Types" of the official documentation: https://www.typescriptlang.org/docs/handbook/advanced-types.html

1

To be fair there are many ways to type actions but I find this one very straight forward and has the less possible boilerplate as well (already discussed in this topic).

This approach tries to type the key called "payload" of actions.

Check this sample

1

Lately I have been using this approach:

export abstract class PlainAction {
    public abstract readonly type: any;
    constructor() {
        return Object.assign({}, this);
    }
}

export abstract class ActionWithPayload<P extends object = any> extends PlainAction {
    constructor(public readonly payload: P) {
        super();
    }
}

export class BeginBusyAction extends PlainAction {
    public readonly type = "BeginBusy";
}

export interface SendChannelMessageActionPayload {
    message: string;
}

export class SendChannelMessageAction
    extends ActionWithPayload<SendChannelMessageActionPayload>
{
    public readonly type = "SendChannelMessage";
    constructor(
        message: string,
    ) {
        super({
            message,
        });
    }
}

This here:

constructor() {
    return Object.assign({}, this);
}

ensures that the Actions are all plain objects. Now you can make actions like this: const action = new BeginBusyAction(). (yay \o/)

1

I am the author of ts-redux-actions-reducer-factory and would present you this as an another solution on top of the others. This package infers the action by action creator or by manually defined action type and - that's new - the state. So each reducer takes aware of the return type of previous reducers and represents therefore a possible extended state that must be initialized at the end, unless done at beginning. It is kind of special in its use, but can simplify typings.

But here a complete possible solution on base of your problem:

import { createAction } from "redux-actions";
import { StateType } from "typesafe-actions";
import { ReducerFactory } from "../../src";

// Type constants
const aType = "a";
const bType = "b";

// Container a
interface IActionA {
    a: string;
}

// Container b
interface IActionB {
    b: string;
}

// You define the action creators:
// - you want to be able to reduce "a"
const createAAction = createAction<IActionA, string>(aType, (a) => ({ a }));
// - you also want to be able to reduce "b"
const createBAction = createAction<IActionB, string>(aType, (b) => ({ b }));

/*
 * Now comes a neat reducer factory into the game and we
 * keep a reference to the factory for example purposes
 */
const factory = ReducerFactory
    .create()
    /*
     * We need to take care about other following reducers, so we normally want to include the state
     * by adding "...state", otherwise only property "a" would survive after reducing "a".
     */
    .addReducer(createAAction, (state, action) => ({
        ...state,
        ...action.payload!,
    }))
    /*
     * By implementation you are forced to initialize "a", because we
     * now know about the property "a" by previous defined reducer.
     */
    .addReducer(createBAction, (state, action) => ({
        ...state,
        ...action.payload!,
    }))
    /**
     * Now we have to call `acceptUnknownState` and are forced to initialize the reducer state.
     */
    .acceptUnknownState({
        a: "I am A by default!",
        b: "I am B by default!",
    });

// At the very end, we want the reducer.
const reducer = factory.toReducer();

const initialState = factory.initialKnownState;
// { a: "I am A by default!", b: "I am B by default!" }

const resultFromA = reducer(initialState, createAAction("I am A!"));
// { a: "I am A!", b: "I am B by default!" }

const resultFromB = reducer(resultFromA, createBAction("I am B!"));
// { a: "I am A!", b: "I am B!" }

// And when you need the new derived type, you can get it with a module like @typesafe-actions
type DerivedType = StateType<typeof reducer>;

// Everything is type-safe. :)
const derivedState: DerivedType = initialState;
1

Here is how can you do it with redux-fluent:

enter image description here enter image description here

1

I think a lot of these answers are two or three steps of abstractions away. The action creator factory is nice and all but typescript is pretty bad for mixins and the like. I want something readable.

// types
export interface IType<T = any> {
  type: T;
}
export interface IPayload { 
// where primitives are specifically number , string , boolean, and custom class Nothing.
   storeTLD: string, storeKey: string, storeValue: TPrimitives
}
export interface IAction extends IType<string> {
  type: string;
  payload?: IPayload;
}
export interface IActions extends IType<string> {
  type: string;
  payloads: IPayload[]
}
// begin action registry
export type TSetUserDataAction = ReturnType<typeof setUserDataAction>;
export type TUserActions = TSetUserIdAction; // and other actions

export const setUserIdAction = (
  payload: IUserIdPayload
): IAction => ({
  type: SET_USER_ID,
  payload,
});

const [state, appSingleSlotDispatch] = useReducer(appSingleSlotReducer,initialState);

appSingleSlotDispatch(setUserIdAction({destination: 'user', storeKey: 'id", storeValue: someFetchedPrimitive})

const appSingleSlotReducer = (state, action: IAction) => {
  const appReduce = (state,{storeTLD,storeKey,storeValue}:IPayload) => { 
    const newState = {...state}
    newState[storeTLD][storeKey] = storeValue
    return newState
  }
  switch (action.type) {
    case SET_USER_ID:
      return appReduce(state, action.payload)
  }
  return state;
}
const appMultiSlotReducer = (state: IInitialState, action: IActions) => {
   return action.payloads.reduce(appReduce, {...state})
}

You could overload your reducers but then again it'd be harder to read and you need more ts to support it. At the very least, 90% of your code uses these simple primitive reducers. When the business logic calls for something more advanced with more nested objects, you create an appSuperReducer.

Is an abstracted factory more readable than something that says multiSlotAppReducer? Do you nest more than 2 levels deep? If you are nesting that deep, then you'd benefit more with graphql/relay, with its reusable interfaces and ease of nested objects.

At the end of the day, generics are another way of overloading, and overloading is the enemy of single responsibility principle. If we can reliably ensure that the two logical reductions will apply to the same shape, then I think we can make a contract between them, apply generics, have our polymophism cake. But redux state is the first to be slammed by changing requirements which is the enemy of polymorphism.

That's my opinion.

1

The problem with the previous answers is that you need to know all your actions beforehand. This is both unwieldy and unnecessarily coupling.

The simplest and most robust thing to do is simply to type the type as string, and the payload as unknown, then assert the type where you need it using a type-predicate:

function actionIsA(action: Action): action is IActionA {
  return (action as IActionA).a !== undefined;
}

function actionIsB(action: Action): action is IActionB {
  return (action as IActionB).b !== undefined;
}

const reducer = (state, action: Action) {
    switch (action.type) {
        case 'a':
            return actionIsA(action) && console.info('action a: ', action.a); // no errors

        case 'b':
            return actionIsB(action) && console.info('action b: ', action.b); // also no errors
    }
}

// or better (in my opinion)
const reducer = (state action: Action) {
  if (actionIsA(action)) {
    console.info('action a: ', action.a);
  }

  if (actionIsB(action)) {
    console.info('action b: ', action.b);
  }
}
1

For me the more important thing was to type the Actions and Dispatching inside my components/services.

So the simplest thing I could think of was doing this (with inspiration from the Redux typescript guid):

Make a custom hook just for typing the action:

./hooks.ts

import { useDispatch} from 'react-redux';

export const useAppDispatch: () => (action: IActionModel) => void = useDispatch

And then using it in my component:

./component.tsx

import {useAppDispatch} from "./hooks";

export const Component () => {
...
const dispatch = useAppDispatch();
myHandler () {
   const myAction : IAction = {type: 'foo', payload :'bar'};
   dispatch(myAction) 
   // This is where your IDE/ Linter ect. will
   // do the type checks and will not allow you to insert 
   // a badly typed Object. 
}

...
}

This gives a certain advantage which is you only have to define the IAction how ever you like (with all the different typescript features including union etc.) and then just use it in your component and get the type checking.

-3

Here's the approach I've taken for this problem:

const reducer = (action: IAction) {

    const actionA: IActionA = action as IActionA;
    const actionB: IActionB = action as IActionB;

    switch (action.type) {
        case 'a':
            // Only ever use actionA in this context
            return console.info('action a: ', actionA.a)

        case 'b':
            // Only ever use actionB in this context
            return console.info('action b: ', actionB.b)
    }
}

I'll be the first to admit there's a certain ugliness and hackiness to this approach, but I've actually found it to work pretty well in practice. In particular, I find that it makes the code easy to read and maintain because the action's intent is in the name and that also makes it easy to search for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.