I am seeking to define a specific type for my "reducer" function.
The "reducer" function I have takes in 2 parameters: the current state and the data sent in the dispatch context (to be used by the reducer).
const reducer = (
state: any,
props: {
action: string,
value: any,
}
) => {
...
}
The second parameter will always be an object with 2 properties: action and value.
However, I am not comfortable allowing just any value for the "value" property. Hence, I wish to create a dynamic "type".
I already have an interface containing all the information present in my context.
DefaultValueContextInterface interface {
floatMsgError: string;
isOpenSidebar: boolean;
.....
}
What I aim for is that this new "type" I want to establish only permits something like:
{
action: "floatMsgError",
value: string,
}
Why restrict "value" to only "string"? Because in the interface "DefaultValueContextInterface", the property "floatMsgError" is of type string. Similarly, each property in the "DefaultValueContextInterface" interface follows the same pattern automatically. If the value for "action" passed to the "reducer" function matches "isOpenSidebar", then the corresponding "value" must be of type boolean.
I could manually create the type like so:
{
action: "floatMsgError",
value: string,
}
| {
action: "isOpenSidebar",
value: boolean,
}
However, having numerous properties within my context makes manual creation impractical.
I also attempted using "[P in keyof DefaultValueContextInterface]" but was only able to combine it as follows:
type Props = {
[P in keyof DefaultValueContextInterface]: {
action: P;
value: DefaultValueContextInterface[P];
};
};
This doesn't suit my needs because it generates an object which isn't the desired outcome. Nonetheless, the nested objects do align closely with what I require. I just need to figure out a different looping mechanism to achieve it.
At present, I have this:
type Props = {
action: keyof DefaultValueContextInterface;
value: DefaultValueContextInterface[keyof DefaultValueContextInterface];
};
However, this does not effectively link the values of "action" and "value" together :/