Created
September 29, 2016 16:00
-
-
Save rjz/87634d627911f90c7c84a03f39fa198a to your computer and use it in GitHub Desktop.
Redux actions using TypeScript discriminated unions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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