The syntax is, I think, somewhat clunky, but the idea is that you start out with an enum with your action types:
enum Kind {
ShowAll,
SetStatus
}
Then the actual discriminated union with whatever data each action type needs:
type Action = {
kind : Kind.ShowAll
payload : boolean
}
| {
kind : Kind.SetStatus
index : number
status : string
}
In your reducer you can now switch on kind:
function stepsReducer(steps: IFormStep[], action: Action) {
switch (action.Kind)
{
case Kind.ShowAll:
// You can now access action.payload and do whatever...
break;
case Kind.SetStatus:
// You can now access action.index and action.status
break;
default:
// This mostly seems like black magic to me, but it has the compiler
// warn when you have NOT switched on ALL action types:
const _exhaustiveCheck: never = action;
}
}
It is fairly elegant, although perhaps a bit convoluted, but you have the compiler help you out quite bit :)
Engineer | Lover of dogs, books, and learning | Dos XX can be most interesting man in the world, I'm happy being the luckiest. | I write about what I learn @ code-comments.com
You may want to look into discriminated unions : typescriptlang.org/docs/handbook/a...
The syntax is, I think, somewhat clunky, but the idea is that you start out with an enum with your action types:
Then the actual discriminated union with whatever data each action type needs:
In your reducer you can now switch on kind:
It is fairly elegant, although perhaps a bit convoluted, but you have the compiler help you out quite bit :)
Very nice! Thank you!