I'm trying to type check my redux-thunk
code with Typescript.
From the official docs of Redux: Usage with Redux Thunk, we get this example:
// src/thunks.ts
import { Action } from 'redux'
import { sendMessage } from './store/chat/actions'
import { RootState } from './store'
import { ThunkAction } from 'redux-thunk'
export const thunkSendMessage = (
message: string
): ThunkAction<void, RootState, unknown, Action<string>> => async dispatch => {
const asyncResp = await exampleAPI()
dispatch(
sendMessage({
message,
user: asyncResp,
timestamp: new Date().getTime()
})
)
}
function exampleAPI() {
return Promise.resolve('Async Chat Bot')
}
To reduce repetition, you might want to define a reusable AppThunk type once, in your store file, and then use that type whenever you write a thunk:
export type AppThunk<ReturnType = void> = ThunkAction<
ReturnType,
RootState,
unknown,
Action<string>
>
QUESTION
I'm not fully understanding the use of the ThunkAction
type:
ThunkAction<void, RootState, unknown, Action<string>>
There are 4 type params, right?
1st - void
This is the return type of the thunk, right? Shouldn't it be Promise<void>
, since it's async
?
2nd - RootState
It's the full state shape, right? I mean, it's not a slice, but the full state.
3rd - unknown
Why is this unknown
? What is this?
4th - Action<string>
Also didn't understand this. Why is Action<T>
taking a string as a parameter? Should it always be string
? Why is it?