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; | |
} | |
} |
I prefer an tech/language agnostic construct either(), because you can do it any "lambda" enabled language.
function either(f, g) {
return function () {
return f.apply(this, arguments) || g.apply(this, arguments);
}
}
const gt10 = x => x > 10;
const even = x => x % 2 === 0;
const f = either(gt10, even);
console.log(f(7))
console.log(f(100))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey guys,
you may want to have a look on @mhoyer's project redux-typed-ducks.
The idea is to wrap
Actions
in a context (action-creator-function
) providing better typing-support.It builds an abstraction layer on top of Actions.