Skip to content

Type payload-less slice action creators to take no arguments #110

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions src/createSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ import { createSliceSelector, createSelectorName } from './sliceSelector'
/**
* An action creator atttached to a slice.
*/
export type SliceActionCreator<P> = (payload: P) => PayloadAction<P>
export type SliceActionCreator<P, T extends string = string> = P extends void
? () => Action<T>
: (payload: P) => PayloadAction<P, T>

export interface Slice<
S = any,
A extends Action = AnyAction,
AP extends { [key: string]: any } = { [key: string]: any }
> {
/**
Expand All @@ -21,13 +22,15 @@ export interface Slice<
/**
* The slice's reducer.
*/
reducer: Reducer<S, A>
reducer: Reducer<S>

/**
* Action creators for the types of actions that are handled by the slice
* reducer.
*/
actions: { [type in keyof AP]: SliceActionCreator<AP[type]> }
actions: {
[type in keyof AP]: SliceActionCreator<AP[type], Extract<type, string>>
}

/**
* Selectors for the slice reducer state. `createSlice()` inserts a single
Expand Down Expand Up @@ -101,9 +104,7 @@ export function createSlice<
S = any,
A extends PayloadAction = PayloadAction<any>,
CR extends CaseReducersMapObject<S, A> = CaseReducersMapObject<S, A>
>(
options: CreateSliceOptions<S, A, CR>
): Slice<S, A, ExtractPayloads<S, A, CR>> {
>(options: CreateSliceOptions<S, A, CR>): Slice<S, ExtractPayloads<S, A, CR>> {
const { slice = '', initialState } = options
const reducers = options.reducers || {}
const extraReducers = options.extraReducers || {}
Expand Down
5 changes: 5 additions & 0 deletions type-tests/files/createSlice.typetest.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
Action,
AnyAction,
createSlice,
PayloadAction,
Expand Down Expand Up @@ -64,6 +65,10 @@ import {
}
})

const increment: () => Action<'increment'> = counter.actions.increment
const multiply: (payload: number) => PayloadAction<number, 'multiply'> =
counter.actions.multiply

counter.actions.increment()
counter.actions.multiply(2)

Expand Down