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.
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
Asked: 2022-06-04 11:00:00 +0000
Seen: 9 times
Last updated: Mar 26 '23
How can Django Admin accommodate a variety of formats and locales for its input fields?
How can an array be passed using typo3 flexform xml and itemsProcConfig?
Is it possible to invoke an asynchronous function without using the await keyword?
How can metadata be linked to a series in Polars?
What is the process of utilizing the map function to map a pandas column using a dictionary?
How can the orientation of images be corrected during uploading using Plupload?