Skip to content

Instantly share code, notes, and snippets.

@DimitryDushkin
Created September 27, 2018 19:34
Show Gist options
  • Save DimitryDushkin/fe7ad6a6f82c6e9a12e757efb5f4121e to your computer and use it in GitHub Desktop.
Save DimitryDushkin/fe7ad6a6f82c6e9a12e757efb5f4121e to your computer and use it in GitHub Desktop.
Curry functions in map for Typescript
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