Skip to content

Instantly share code, notes, and snippets.

@quicksnap
Last active January 16, 2018 00:23
Show Gist options
  • Save quicksnap/80f854d9b4fb22c1235162473e39cb81 to your computer and use it in GitHub Desktop.
Save quicksnap/80f854d9b4fb22c1235162473e39cb81 to your computer and use it in GitHub Desktop.
// actions.ts
// Every action in the entire application would be part of this union type
type MyActions =
AddToCartAction | FilterItemsAction | SomeOtherAction /* ... */;
// reducer.ts
function reducer(state: MyAppState, action: MyActions) {
// action has type MyAction, which contains every possible action
if (action.type === 'ADD_TO_CART') {
// Since only one action has `type` === 'ADD_TO_CART', TypeScript
// knows the narrowed type of this action has `payload.productIds`
const addedProductIds = action.payload.productIds;
// etc...
}
if (action.type === 'FILTER_ITEMS') {
// Also type-safe
const filter = action.payload.filterType;
// etc...
}
return state;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment