In my Redux store, I want to create a reducer that can modify any attribute values within the store.
Consider the state
object defined with specific types:
type StoreState = {
admins: Admin[];
messages: Message[];
pageInformation: PageInformation;
}
const state: StoreState = {
admins: [],
messages: [],
pageInformation: {},
}
Let's think of a function that is not a reducer, just for illustration purposes.
const setPropertyValue = ({ propName, propValue }) => {
state[propName] = propValue;
}
In this function, it would be beneficial to assign types to propName
and propValue
.
For instance, if the value of propName
is "admins", then propValue
should match the type of StoreState[propName]
, which is Admin[]
:
setPropertyValue({ propName: "admins", propValue: [...] });
I have explored various approaches and consulted different resources, however, Typescript does not seem to support this feature at the moment.
Here is an example that highlights the limitation:
type SetPropertyValue = {
propName: keyof StoreState;
propValue: StoreState[SetPropertyValue[propName]];
}
const setPropertyValue = ({ propName, propValue }: SetPropertyValue) => {
state[propName] = propValue;
}
This particular approach fails because propName
is not strictly a key of StoreState
, but rather a union type composed of keys from StoreState
.