Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rjz/87634d627911f90c7c84a03f39fa198a to your computer and use it in GitHub Desktop.
Save rjz/87634d627911f90c7c84a03f39fa198a to your computer and use it in GitHub Desktop.
Redux actions using TypeScript discriminated unions
// Redux actions using TypeScript discriminated unions
//
// Source: https://github.com/rjz/typescript-react-redux/
// Actions
export type Action =
{ type: 'INCREMENT_COUNTER', delta: number }
| { type: 'RESET_COUNTER' }
type Counter = { value : number }
// Reducer
function counter (state: Counter = { value: 0 }, action: Action): Counter {
switch (action.type) {
case 'INCREMENT_COUNTER':
// Since `INCREMENT_COUNTER` only matches one type in the union, the
// compiler allows us to extract additional fields (i.e., `delta`) from
// the action without casting.
const { delta } = action
return { value: state.value + delta }
case 'RESET_COUNTER':
return { value: 0 }
// compilation will fail for any types / `case`s that aren't declared in
// the `Action` union.
default:
return state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment