Wie richte ich Redux mit TypeScript ein?

Posted . Visible to the public.

Example Action

Action types werden über enums typisiert.

import { Action } from 'redux';

export const key = 'general';

export enum StartActionTypes {
  START = 'START'
}

export function start() {
  return {
    type: StartActionTypes.START,
  };
}

export interface StartAction extends Action {
    type: StartActionTypes;
}

Example Reducer

Jeder Reducer definiert seinen eigenen State-Type und nutzt den definierten Action-Type aus der entsprechenden action.ts.

import { StartAction, StartActionTypes } from './actions';

const initialState: GeneralState = {
  amountStarted: 0,
};

export interface GeneralState {
  amountStarted: number;
}

export function startReducer(state = initialState, action: StartAction) {
  switch (action.type) {
    case StartActionTypes.START: {
      state.amountStarted++;
      return state;
    }
    default:
      return state;
  }
}

Example RootReducer

Der Type des States der gesamten App setzt sich dann aus den Types aus den einzelnen Reducer zusammen.

import { combineReducers, Action } from 'redux';
import { startReducer, GeneralState } from './start/reducer';
import {key as startKey} from './start/actions';

export interface AppState  {
  [startKey]: GeneralState
}

const appReducer = combineReducers({
  [startKey]: startReducer,
});

export default function rootReducer(state: AppState | undefined, action: Action) {
  return appReducer(state, action);
}
Nikolai Kratz
Last edit
Nikolai Kratz
Posted by Nikolai Kratz to Appdafuer (2018-09-20 12:13)