【发布时间】:2021-01-01 00:05:38
【问题描述】:
我正在尝试使用 Typescript 输入检查我的 redux-thunk 代码。
从 Redux 的官方文档:Usage with Redux Thunk,我们得到这个例子:
// 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')
}
为减少重复,您可能希望在商店文件中定义一次可重用的 AppThunk 类型,然后在编写 thunk 时使用该类型:
export type AppThunk<ReturnType = void> = ThunkAction<
ReturnType,
RootState,
unknown,
Action<string>
>
问题
我没有完全理解 ThunkAction 类型的用法:
ThunkAction<void, RootState, unknown, Action<string>>
有 4 个类型参数,对吧?
第一 - void
这是 thunk 的返回类型,对吧?不应该是Promise<void>,因为它是async?
第二次 - RootState
这是完整的状态形状,对吗?我的意思是,它不是切片,而是完整的状态。
第三 - unknown
为什么是unknown?这是什么?
第 4 次 - Action<string>
这个也不明白。为什么Action<T> 将字符串作为参数?它应该总是string 吗?为什么会这样?
【问题讨论】:
标签: typescript redux typescript-typings redux-thunk