More complex clarification of stream type in switch statements
Suppose I have code like this where I have 2 types of objects and I am trying to use refinement in a switch statement which will support more complex cases
/* @flow */
type Add = {
type: "add",
someAddSpecificStuff: 3,
};
type Sub = {
type: "sub",
};
type Actions =
| Add
| Sub;
function reducer(model: number = 0, action: Actions): number {
switch(true) {
case action.type === "add":
return model + 1 + action.someAddSpecificStuff;
case action.type === "sub":
return model - 1;
default:
return model;
}
}
This gives me:
27: return model + 1 + action.addSpecific; ^ property
addSpecific
. Property not found in27: return model + 1 + action.addSpecific; ^ object type
If I do the following, it obviously works:
switch (action.type) {
case "add":
...
The reason I am trying to use the above pattern is to trap all types stored in an array, for example, and reuse this function for everyone, for example:
switch(true) {
case BIG_ARRAY_OF_OBJECT_TYPES.includes(action.type) {
return action.somethingIKnowThatIsAlwaysPresentInTheseActions;
}
}
How is this usually done?
+3
source to share
No one has answered this question yet
Check out similar questions: