-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
52 lines (40 loc) · 1.64 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
export type ActionCreator<T extends string> = {
actionType: T,
(): { type: T };
};
export type ActionCreatorWithPayload<T extends string, Payload, Args extends Array<any>> = {
actionType: T,
(...args: Args): { type: T, payload: Payload },
};
export type KeysToFunctions = {
[key: string]: (...args: Array<any>) => any;
};
export type ActionTypeFromActionCreators<T extends KeysToFunctions> = ReturnType<T[keyof T]>;
export function createAction<T extends string>(
type: T,
): ActionCreator<T>;
export function createAction<T extends string, Payload, Args extends Array<any>>(
type: T,
payloadCreator: (...args: Args) => Payload,
): ActionCreatorWithPayload<T, Payload, Args>;
export function createAction<T extends string, Payload, Args extends Array<any>>(
type: T,
payloadCreator?: (...args: Args) => Payload,
): ActionCreatorWithPayload<T, Payload, Args> | ActionCreator<T> {
if (payloadCreator == null) {
const action = { type };
// TypeScript gives type errors when using object spread (ie. { ...x })
// with functions, so we have to use Object.assign here instead.
// tslint:disable-next-line:prefer-object-spread
return Object.assign(() => action, { actionType: type });
} else {
const f = (...args: Args) => ({
payload: payloadCreator(...args),
type: type,
});
// TypeScript gives type errors when using object spread (ie. { ...x })
// with functions, so we have to use Object.assign here instead.
// tslint:disable-next-line:prefer-object-spread
return Object.assign(f, { actionType: type });
}
}