Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One method for typing a general key in the Redux Toolkit reducer would be to use a string literal type that represents the key as the index type. This is a workaround for the limitation of not being able to use keyof T as an index type. Here is an example:

interface MyState {
  foo: number;
  bar: string;
}

type MyKey = 'foo' | 'bar';

const myReducer = createReducer<MyState>({ foo: 0, bar: '' }, {
  [myKey]: (state, action: PayloadAction<number | string>) => {
    state[myKey] = action.payload;
  }
});

In this example, we define a MyKey type that represents the keys of MyState. We use this type as the index type in the reducer function, which allows us to access and update the state using the key as a string literal. This approach still provides compile-time safety because we are using a known set of keys defined in the MyKey type.