Ask Your Question
0

What is the method for typing a general key in the redux toolkit reducer, given the limitation that the 'keyof T' type cannot be utilized as an index type?

asked 2022-06-04 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-03-26 03:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-04 11:00:00 +0000

Seen: 9 times

Last updated: Mar 26 '23