Redux Toolkit TS:元素隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引类型 'WritableDraft<configSlice>'

Redux Toolkit TS: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'WritableDraft<configSlice>'

我有一个公共调度程序来更新多个状态,如下所示:

updateConfiguration: (state, action) => {
            const { type, payload } = action.payload
            const { dispatchKey, stateKey } = keyHelpers[type as keyof keyHelpersType]

            state[stateKey] = payload[dispatchKey]
        }

其中keyHelpers如下图:

export const keyHelpers: keyHelpersType = {
    [actionTypes.addUser]: {
        dispatchKey: 'user',
        stateKey: 'user',
    }

在我的减速器中编写调度逻辑时,我在以下行中收到以下错误:

state[stateKey] = payload[dispatchKey] 错误: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'WritableDraft<configSlice>'

我试过:

state[stateKey as keyof typeof state] = payload[dispatchKey]

但这并不能很好地投掷:

Type 'any' is not assignable to type 'never'.ts(2322) 有人可以帮我解决这个问题吗?

您可能需要添加一个 as const 断言:

export const keyHelpers: keyHelpersType = {
    [actionTypes.addUser]: {
        dispatchKey: 'user',
        stateKey: 'user',
    }
} as const

这样就不会是 string,而是 "user"