by bcherny · 10y ago · 0 comments
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.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.