使用打字稿设置reducer react redux

时间:2018-10-11 10:04:32

标签: javascript reactjs typescript react-redux

我正在使用redux设置ts并遇到了很多问题-主要是由于我缺乏知识,但在网上找不到太多东西。我看到的错误如下:

  

运算符'+'不能应用于类型'CounterState'和'1'。

我的代码如下:

interface CounterState {
  state: number;
}

const initialState: CounterState = {
  state: 0
}

interface Action {
  type: string;
}

export const counterReducer = (state = initialState, action: Action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
};

如果我对此进行更新,则可以使用,但是似乎不必为状态定义类型。以下作品

const initialState = 0;
interface Action {
  type: string;
}

export const counterReducer = (state = initialState, action: Action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
};

1 个答案:

答案 0 :(得分:1)

优良作法是始终强烈键入状态和动作的减速器。

在这里,我展示了一个示例,说明正确定义的reducer和store看起来如何在一起。 希望这个示例以及我的评论对您有所帮助。

import { Reducer } from "redux"; //This is just a Type we import from Redux.

interface IncrementAction {
  type: "INCREMENT"; //Define your action names
}

interface DecrementAction {
  type: "DECREMENT"; //Define your action names
}

type PossibleCounterActions = IncrementAction | DecrementAction; 
// The actions could/should be defined in another file for clarity


type CounterState = number;

const defaultState = 0;

// We bind the variable counterReducer to the Reducer type taken from redux.
// The our reducer code gets cleaner and we know the return type and arguments.
const counterReducer: Reducer<CounterState, PossibleCounterActions> = (state = defaultState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
}



// PS. This is not part of the question but it's
// a nice side-effect you can do when you have properly defined reducers.
// In the file where you create your store you can now get your store
// interface from the returntype of the redcuers using this pattern. 
const reducers = {
  counter: counterReducer
};

// Now we can get the entire store state from the declaration in the reducers.
export type IStoreState = { [k in keyof (typeof reducers)]: ReturnType<(typeof reducers)[k]> };

//More code to initialize your store.....