Skip to content

Instantly share code, notes, and snippets.

@brunolm
Last active November 6, 2017 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunolm/257a4f60bcfd85fcdef81476ddbc3960 to your computer and use it in GitHub Desktop.
Save brunolm/257a4f60bcfd85fcdef81476ddbc3960 to your computer and use it in GitHub Desktop.
React Redux - Action creator (prototype)
/* Prototype
- Trying to make return type of Creators include the property TYPE
*/
function createActions<T>(obj: T) {
const keys = Object.keys(obj);
return {
Creators: keys.reduce((creators, key) => {
creators[key] = (...args) => ({ type: key, ...obj[key](...args) });
return creators;
}, {}) as typeof obj,
Types: keys.reduce((types, key) => { types[key] = key; return types; }, {}) as { [key in keyof T]: string },
};
}
interface Action {
type?: string;
}
interface LoginAction extends Action {
username: string;
password: string;
}
const { Creators, Types } = createActions({
login: (login: LoginAction) => ({ ...login }),
reset: () => undefined,
});
const loginAction = Creators.login({ username: 'brunolm', password: '123' });
const resetAction = Creators.reset();
console.log(loginAction);
console.log(resetAction);
console.log('Types.login', Types.login);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment