You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Redux Toolkit+TS报错:string类型无法索引WritableDraft<CounterState>如何解决

错误原因

你的核心问题出在两个地方:

  1. updateFieldObject 接口中 fieldName 的类型是无限制的 string,TypeScript 无法确认这个字符串一定是 CounterState 上存在的属性,所以无法用来索引state
  2. 你之前断言用的 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 07:45:01