我正在使用 redux 设置 ts 并遇到了很多问题 - 主要是由于我缺乏知识,但在网上找不到太多。我看到的错误如下:
Operator '+' cannot be applied to types 'CounterState' and '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;
}
};
最佳答案
最好始终强类型化你的 reducer,包括状态和 Action 。
这里我展示了一个正确定义的 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.....
关于javascript - 使用 typescript react redux 设置 reducer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52757383/