Created
September 27, 2018 19:34
-
-
Save DimitryDushkin/fe7ad6a6f82c6e9a12e757efb5f4121e to your computer and use it in GitHub Desktop.
Curry functions in map for Typescript
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
import {Provider, Consumer} from 'react'; | |
// tslint:disable-next-line | |
type Curry<F extends Function> = F extends (arg1: infer T1, arg2: infer T2, arg3: infer T3) => any | |
? (arg3: T3) => ReturnType<F> | |
: never; | |
type RVSActionCreator<S, A> = (state: S, actions: A, arg: any) => any; | |
type ActionCreatorsMap<S, A> = {[actionName: string]: RVSActionCreator<S, A>}; | |
type RVSStore<S, RVSActions> = { | |
Provider: Provider<S>, | |
Consumer: Consumer<S>, | |
actions: RVSActions, | |
}; | |
export function createStore< | |
S, | |
A extends ActionCreatorsMap<S, A>, | |
FinalActions extends {[K in keyof A]: Curry<A[K]>} | |
>(initialState: S, actions: A): RVSStore<S, FinalActions> { | |
const exportedFunctions: FinalActions = {} as FinalActions; | |
Object.keys(actions).forEach(key => { | |
exportedFunctions[key] = arg => actions[key](initialState, exportedFunctions, arg); | |
}); | |
return { | |
Provider: {} as any, | |
Consumer: {} as any, | |
actions: exportedFunctions, | |
}; | |
} | |
const inputState = { | |
stateProperty: 1, | |
}; | |
const inputActions = { | |
start: (_, __, a: number) => { | |
return Promise.resolve(a); | |
}, | |
}; | |
const store = createStore( | |
inputState, | |
inputActions, | |
); | |
store.actions.start(1); | |
store.actions.start('a'); // expected error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment