Skip to content

Instantly share code, notes, and snippets.

@jrwebdev
Last active July 23, 2019 20:07
Show Gist options
  • Save jrwebdev/1369bdfed1a1c4836b9b351c2cd8bb72 to your computer and use it in GitHub Desktop.
Save jrwebdev/1369bdfed1a1c4836b9b351c2cd8bb72 to your computer and use it in GitHub Desktop.
interface State {
value: number;
}
type Action =
| { type: 'increment' }
| { type: 'decrement' }
| { type: 'incrementAmount'; amount: number };
const counterReducer = (state: State, action: Action) => {
switch (action.type) {
case 'increment':
return { value: state.value + 1 };
case 'decrement':
return { value: state.value - 1 };
case 'incrementAmount':
return { value: state.value + action.amount };
default:
throw new Error();
}
};
const [state, dispatch] = useReducer(counterReducer, { value: 0 });
dispatch({ type: 'increment' });
dispatch({ type: 'decrement' });
dispatch({ type: 'incrementAmount', amount: 10 });
// TypeScript compilation error
dispatch({ type: 'invalidActionType' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment