fetchSomething
的定义如下:
export const fetchSomething = createAsyncThunk(
'something',
async () => {
return Promise.resolve({name: 'jack'})
}
)
这是 React 组件内的代码:
const dispatch = useAppDispatch()
const getMessages = async () => {
const result = await dispatch(fetchSomething())
return result.payload
}
result
具有正确的 Typescript 类型,而 result.payload
属于 unknown
类型
const result: PayloadAction<{name: string}, string, {arg: void, requestId: string, requestStatus: "fulfilled"}, never> | PayloadAction<unknown, string, {arg: void, requestId: string, requestStatus: "rejected", aborted: boolean, condition: boolean}, SerializedError>
我在官方文档上找到了相关信息,但我不知道如何在我的例子中使用:
import { UnknownAction } 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, UnknownAction> =>
async dispatch => {
const asyncResp = await exampleAPI()
dispatch(
sendMessage({
message,
user: asyncResp,
timestamp: new Date().getTime()
})
)
}
function exampleAPI() {
return Promise.resolve('Async Chat Bot')
}
我希望
getMessages
方法返回正确的类型 Promise<{name: string}>
我按照@timotgl的建议再次查询文档,找到了这个section,并对代码进行了更改,但问题仍然存在,
result.payload
的类型仍然是unknown
。
export const fetchSomething = createAsyncThunk<{name: string}>(
'something',
async () => {
return Promise.resolve({name: 'jack'})
}
)
更新 fetchSomething 的定义以使用自定义类型:
export const fetchSomething = createAsyncThunk<{name: string}, void>(
'something',
async () => {
return Promise.resolve({ name: 'jack' });
}
);
在 getMessages 函数中设置正确的结果类型:
const getMessages = async (): Promise<{name: string}> => {
const result = await dispatch(fetchSomething());
return result.payload;
};
现在,getMessages方法将返回正确的Promise类型<{name: string}>
希望这对您有帮助。