Skip to content

Fix PayloadAction inference #138

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

Merged
merged 2 commits into from
Jul 6, 2019
Merged
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
6 changes: 5 additions & 1 deletion src/createSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@ import { createSliceSelector, createSelectorName } from './sliceSelector'

/**
* An action creator atttached to a slice.
*
* The `P` generic is wrapped with a single-element tuple to prevent the
* conditional from being checked distributively, thus preserving unions
* of contra-variant types.
*/
export type SliceActionCreator<P> = P extends void
export type SliceActionCreator<P> = [P] extends [void]
? () => PayloadAction<void>
: (payload: P) => PayloadAction<P>

Expand Down
6 changes: 5 additions & 1 deletion type-tests/files/createSlice.typetest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,16 @@ import {
reducers: {
increment: state => state + 1,
decrement: state => state - 1,
multiply: (state, action: PayloadAction<number>) => state * action.payload
multiply: (state, { payload }: PayloadAction<number | number[]>) =>
Array.isArray(payload)
? payload.reduce((acc, val) => acc * val, state)
: state * payload
}
})

counter.actions.increment()
counter.actions.multiply(2)
counter.actions.multiply([2, 3, 4])

// typings:expect-error
counter.actions.multiply()
Expand Down