Skip to content

Commit e729165

Browse files
committed
Add typetest for typical typed hooks usage
1 parent 4a1857c commit e729165

File tree

1 file changed

+80
-8
lines changed

1 file changed

+80
-8
lines changed

test/typetests/react-redux-types.typetest.tsx

+80-8
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,77 @@
22
import { Component, ReactElement } from 'react'
33
import React from 'react'
44
import ReactDOM from 'react-dom'
5-
import { Store, Dispatch, bindActionCreators, AnyAction } from 'redux'
6-
import { connect, Provider, ConnectedProps } from '../../src/index'
5+
import {
6+
configureStore,
7+
createSlice,
8+
createAsyncThunk,
9+
Store,
10+
Dispatch,
11+
bindActionCreators,
12+
AnyAction,
13+
ThunkAction,
14+
Action,
15+
} from '@reduxjs/toolkit'
16+
import {
17+
connect,
18+
Provider,
19+
ConnectedProps,
20+
useDispatch,
21+
useSelector,
22+
TypedUseSelectorHook,
23+
} from '../../src/index'
724
import { expectType } from '../typeTestHelpers'
825

926
import objectAssign from 'object-assign'
1027

11-
//
12-
// Quick Start
13-
// https://github.com/rackt/react-redux/blob/master/docs/quick-start.md#quick-start
14-
//
15-
1628
interface CounterState {
1729
counter: number
1830
}
19-
declare var increment: Function
31+
32+
const initialState: CounterState = {
33+
counter: 0,
34+
}
35+
36+
const counterSlice = createSlice({
37+
name: 'counter',
38+
initialState,
39+
reducers: {
40+
increment(state) {
41+
state.counter++
42+
},
43+
},
44+
})
45+
46+
export function fetchCount(amount = 1) {
47+
return new Promise<{ data: number }>((resolve) =>
48+
setTimeout(() => resolve({ data: amount }), 500)
49+
)
50+
}
51+
52+
export const incrementAsync = createAsyncThunk(
53+
'counter/fetchCount',
54+
async (amount: number) => {
55+
const response = await fetchCount(amount)
56+
// The value we return becomes the `fulfilled` action payload
57+
return response.data
58+
}
59+
)
60+
61+
const { increment } = counterSlice.actions
62+
63+
const counterStore = configureStore({
64+
reducer: counterSlice.reducer,
65+
middleware: (gdm) => gdm(),
66+
})
67+
68+
export type AppDispatch = typeof counterStore.dispatch
69+
export type RootState = ReturnType<typeof counterStore.getState>
70+
export type AppThunk<ReturnType = void> = ThunkAction<
71+
ReturnType,
72+
RootState,
73+
unknown,
74+
Action<string>
75+
>
2076

2177
class Counter extends Component<any, any> {
2278
render() {
@@ -402,3 +458,19 @@ namespace ConnectedPropsTest {
402458
{} as PropsFromRedux2
403459
)
404460
}
461+
462+
// Standard hooks setup
463+
export const useAppDispatch = () => useDispatch<AppDispatch>()
464+
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
465+
466+
function CounterComponent() {
467+
const dispatch = useAppDispatch()
468+
469+
return (
470+
<button
471+
onClick={() => {
472+
dispatch(incrementAsync(1))
473+
}}
474+
/>
475+
)
476+
}

0 commit comments

Comments
 (0)