In my redux slice, I have defined a MyState
interface with the following structure:
interface MyState {
key1: string,
key2: boolean,
key3: number,
}
There is an action named set
which has this implementation:
set: (state: MyState, action: PayloadAction<{key: keyof MyState, value: any}>) => {
const { key, value } = action.payload;
state[key] = value;
},
I aim to strictly validate the keys and values passed in the set()
action based on their types. For example:
set('key1', 1); // -> error: key1 must be a string
set('key1', 'my string value'); // -> no error
set('key2', boolean); // -> no error
set('key2', 'my string value'); // -> error: must be a boolean
Although I came across this function signature definition, I am unsure how to incorporate it within a PayloadAction<any>
type to extend the current type of redux action payload.
function setAttribute<T extends Object, U extends keyof T>(obj: T, key: U, value: T[U]) {
obj[key] = value;
}
Your assistance is greatly appreciated!