Created
November 10, 2016 10:26
-
-
Save MikeBild/ad011e8cdb09c015ee91dcdc136b58b1 to your computer and use it in GitHub Desktop.
Q&A - I wanna understand TypeScript - Part TypeScript Union Types as Redux Action Tags
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
// demonstrate | |
const simulateActions = [ | |
addTodo({text: 'todo 1'}), | |
addTodo({text: 'todo 2'}), | |
toggleTodo({index: 0}), | |
toggleTodo({index: 1}), | |
]; | |
const actual = simulateActions.reduce(todosReducer, []); | |
console.log(actual); |
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
// https://blog.mariusschulz.com/2016/11/03/typescript-2-0-tagged-union-types | |
const ADD_TODO = 'ADD_TODO'; | |
const TOGGLE_TODO = 'TOOGLE_TODO'; | |
const todo = (type, payload) => ({type, payload}); | |
const addTodo = payload => todo(ADD_TODO, payload); | |
const toggleTodo = payload => todo(TOGGLE_TODO, payload); | |
const todosReducer = (state, action) => { | |
switch (action.type) { | |
case ADD_TODO: | |
return [...state, { text: action.payload.text, done: false }]; | |
case TOGGLE_TODO: | |
return state.map((todo, index) => { | |
if (index !== action.payload.index) return todo; | |
return { | |
text: todo.text, | |
done: !todo.done, | |
}; | |
}); | |
default: | |
return state; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@marius
I prefer an tech/language agnostic construct either(), because you can do it any "lambda" enabled language.