How to type Redux actions and Redux reducers in Ty

2019-03-15 01:32发布

问题:

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!

回答1:

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)          
    }
}


回答2:

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;
}


回答3:

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);
  }
}


回答4:

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.



回答5:

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



回答6:

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.



回答7:

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.



回答8:

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({}));


回答9:

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
}


回答10:

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.



回答11:

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;


回答12:

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



回答13:

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



回答14:

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



回答15:

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/)



回答16:

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 }));


回答17:

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



回答18:

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.