How to type Redux actions and Redux reducers in TypeScript?

后端 未结 20 2055
旧时难觅i
旧时难觅i 2020-12-13 03:39

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

20条回答
  •  青春惊慌失措
    2020-12-13 04:15

    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

提交回复
热议问题