Redux Toolkit+TS报错:string类型无法索引WritableDraft<CounterState>如何解决
错误原因
你的核心问题出在两个地方:
updateFieldObject接口中fieldName的类型是无限制的string,TypeScript 无法确认这个字符串一定是CounterState上存在的属性,所以无法用来索引state- 你之前断言用的
keyof updateFieldObject完全是错误方向:updateFieldObject自身的键是fieldName、value,和CounterState的属性没有任何关联,自然无法正确匹配state的索引。
解决方案
第一步:修正updateFieldObject类型定义
将fieldName的范围限定为CounterState的合法键,同时保证value的类型和对应字段的类型匹配:
// 先定义合法字段类型 type CounterStateKey = keyof CounterState; interface UpdateFieldObject<K extends CounterStateKey = CounterStateKey> { fieldName: K; value: CounterState[K]; }
如果你的更新场景只会涉及值为字符串类型的字段,也可以进一步收窄类型:
type CounterStateStringKey = { [K in keyof CounterState]: CounterState[K] extends string ? K : never }[keyof CounterState] interface UpdateFieldObject { fieldName: CounterStateStringKey; value: string; }
第二步:修正reducer写法
不需要额外断言,直接赋值即可:
reducers: { updateField: (state,action:PayloadAction<UpdateFieldObject>)=> { const {fieldName,value} = action.payload; state[fieldName] = value; }, // 其他reducer逻辑 }
其他注意事项
你的代码还存在几处笔误需要修正:
- 你创建的slice实例名为
userSlice,后续导出action时错误写为counterSlice,变量名不匹配 CounterState中没有定义value属性,incrementByAmount和extraReducers中访问state.value会报错incrementAsync这个异步thunk未定义就直接在extraReducers中使用
内容的提问来源于stack exchange,提问作者Shivam Sahil
相关产品推荐
相关产品推荐

