Last active
November 6, 2017 10:49
-
-
Save brunolm/257a4f60bcfd85fcdef81476ddbc3960 to your computer and use it in GitHub Desktop.
React Redux - Action creator (prototype)
This file contains hidden or 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
/* 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