Skip to content

Commit

Permalink
add test "wrapping createSlice should be possible"
Browse files Browse the repository at this point in the history
  • Loading branch information
phryneas committed Dec 23, 2019
1 parent 812d9ce commit b755f9d
Showing 1 changed file with 58 additions and 1 deletion.
59 changes: 58 additions & 1 deletion type-tests/files/createSlice.typetest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
ActionCreatorWithNonInferrablePayload,
ActionCreatorWithoutPayload,
ActionCreatorWithPayload,
ActionCreatorWithPreparedPayload
ActionCreatorWithPreparedPayload,
SliceCaseReducerDefinitions
} from '../../src'

function expectType<T>(t: T) {
Expand Down Expand Up @@ -312,3 +313,59 @@ function expectType<T>(t: T) {
}
})
}

/** Test: wrapping createSlice should be possible */
{
interface GenericState<T> {
data?: T
status: 'loading' | 'finished' | 'error'
}

const createGenericSlice = <
T,
Reducers extends SliceCaseReducerDefinitions<GenericState<T>, Reducers>
>({
name = '',
initialState,
reducers
}: {
name: string
initialState: GenericState<T>
reducers: Reducers // I've tried many different types here. Not final
}) => {
return createSlice({
name,
initialState,
reducers: {
start(state) {
state.status = 'loading'
},
success(state: GenericState<T>, action: PayloadAction<T>) {
state.data = action.payload
state.status = 'finished'
},
...reducers
}
})
}

const wrappedSlice = createGenericSlice({
name: 'test',
initialState: { status: 'loading' } as GenericState<string>,
reducers: {
magic(state) {
state.status = 'finished'
state.data = 'hocus pocus'
}
}
})

expectType<ActionCreatorWithPayload<string>>(wrappedSlice.actions.success)

type WrappedSliceState = Parameters<
(typeof wrappedSlice)['caseReducers']['start']
>[0]
expectType<GenericState<string>>((0 as any) as WrappedSliceState)
// typings:expect-error
expectType<GenericState<number>>((0 as any) as WrappedSliceState)
}

0 comments on commit b755f9d

Please sign in to comment.