Skip to content

Commit 3d1772d

Browse files
committed
Type payload-less slice action creators to take no arguments
Previously, it was not possible to assign a slice action creator without payload to `() => any` because the type was inferred as `(payload: void) => any`. Now we use a conditional type for `SliceActionCreator` that special-cases `void`.
1 parent 04cdb02 commit 3d1772d

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

src/createSlice.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,12 @@ import { createSliceSelector, createSelectorName } from './sliceSelector'
66
/**
77
* An action creator atttached to a slice.
88
*/
9-
export type SliceActionCreator<P> = (payload: P) => PayloadAction<P>
9+
export type SliceActionCreator<P, T extends string = string> = P extends void
10+
? () => Action<T>
11+
: (payload: P) => PayloadAction<P, T>
1012

1113
export interface Slice<
1214
S = any,
13-
A extends Action = AnyAction,
1415
AP extends { [key: string]: any } = { [key: string]: any }
1516
> {
1617
/**
@@ -21,13 +22,15 @@ export interface Slice<
2122
/**
2223
* The slice's reducer.
2324
*/
24-
reducer: Reducer<S, A>
25+
reducer: Reducer<S>
2526

2627
/**
2728
* Action creators for the types of actions that are handled by the slice
2829
* reducer.
2930
*/
30-
actions: { [type in keyof AP]: SliceActionCreator<AP[type]> }
31+
actions: {
32+
[type in keyof AP]: SliceActionCreator<AP[type], Extract<type, string>>
33+
}
3134

3235
/**
3336
* Selectors for the slice reducer state. `createSlice()` inserts a single
@@ -101,9 +104,7 @@ export function createSlice<
101104
S = any,
102105
A extends PayloadAction = PayloadAction<any>,
103106
CR extends CaseReducersMapObject<S, A> = CaseReducersMapObject<S, A>
104-
>(
105-
options: CreateSliceOptions<S, A, CR>
106-
): Slice<S, A, ExtractPayloads<S, A, CR>> {
107+
>(options: CreateSliceOptions<S, A, CR>): Slice<S, ExtractPayloads<S, A, CR>> {
107108
const { slice = '', initialState } = options
108109
const reducers = options.reducers || {}
109110
const extraReducers = options.extraReducers || {}

type-tests/files/createSlice.typetest.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
Action,
23
AnyAction,
34
createSlice,
45
PayloadAction,
@@ -64,6 +65,10 @@ import {
6465
}
6566
})
6667

68+
const increment: () => Action<'increment'> = counter.actions.increment
69+
const multiply: (payload: number) => PayloadAction<number, 'multiply'> =
70+
counter.actions.multiply
71+
6772
counter.actions.increment()
6873
counter.actions.multiply(2)
6974

0 commit comments

Comments
 (0)