2 ms·
I've been using discriminated unions on TS 2 to do this, and works quite well. Example: const INCREMENT: "increment" = "increment"; const DECREMENT: "decr
by saguiar 10y ago
I've been using discriminated unions on TS 2 to do this, and works quite well.
Example:
const INCREMENT: "increment" = "increment";
const DECREMENT: "decrement" = "decrement";
interface Increment {
type: typeof INCREMENT;
payload: {
inc: number;
};
}
interface Decrement {
type: typeof DECREMENT;
payload: {
dec: number;
};
}
interface State {
count: number;
}
type Actions = Increment | Decrement;
function reducer(state: State, action: Actions) {
switch (action.type) {
case INCREMENT: {
const { inc } = action.payload;
return { count: state.count + inc };
}
case DECREMENT: {
const { dec } = action.payload;
return { count: state.count + dec };
}
default:
return state;
}
}
Once TS figures out the action type is INCREMENT, it can infer the type of the payload. You don't need the Actions type either, you can just receive action: Increment | Decrement.
- mpawelski 10y agoYes, I'm doing basically the same (define constant a as literal type, then use "typeof" operator to define action type, and then create alias for all Actions using union type). That's one of the reasons why I miss possibility to tell what is the type of the object that function returns. So I could do something like this (hypothetical syntax) const INCREMENT: "increment" = "increment"; const DECREMENT: "decrement" = "decrement"; function increment(inc: number) { return { type: INCREMENT, inc }; } function decrement(dec: number) { return { type: DECREMENT, dec }; } type Actions = returntypeof increment | returntypeof decrement; So I won't need to write action type when I have action creator method. I hope that in future Typescript devs will add some feature to allow this kind of pattern.