In my Typescript and Redux project, I am looking for a way to enforce type checking for the action parameter of a reducer based on its type. This concept is similar to how Entity Framework maps an enum column to a specific subclass.
Here is an example that I'm working on:
enum ActionType {
doThing1,
doThing2
}
interface Action {
readonly type: ActionType
}
interface Thing1Action extends Action {
readonly payload: Thing1Payload;
}
interface Thing2Action extends Action {
readonly payload: Thing2Payload;
}
interface State {
readonly thing1: Thing1Payload;
readonly thing2: Think2Payload;
}
const initialState: State = {
thing1: null,
thing2: null,
}
function reducer(state = initialState, action: Action): State {
switch (action.type)
{
case ActionType.doThing1:
return {...state, thing1: action.payload };
}
return state;
}
In the code above, I want to restrict the action.payload to only hold a Thing1Payload. Currently, Typescript gives me errors stating that action does not have the property payload or assigns it as any when I don't specify the type for action.
I am specifically interested in achieving this kind of validation during both coding and compiling stages.