我一直在网上寻找不同的资源,试图找到适合我所拥有的解决方案,到目前为止,我认为我有点在破坏我的打字稿集成。我希望在正确设置钩子类型方面有所帮助。
我有一个useUser()
钩子,该钩子将动作分派给我的reducer,并且还从我的商店返回选择器。我已经取得了一些进步,但是我开始有点烦恼了。
挂钩:useUser.ts
useUserActionTypes
,但我认为这没有什么区别,尤其是因为除了返回对象(userData
)或数字之外,我没有返回任何其他东西
(totalPoints
,totalWords
)。FETCH_USER
键入我的调度的类型中。可能无关紧要,但是我认为其中应该有保护措施,对吧?User
的类型,它代表我的商店将为用户使用的对象,但是...没什么区别。import { useSelector, useDispatch } from 'react-redux';
import axios from 'axios';
import { User } from '../reducers/user';
export const FETCH_USER = 'FETCH_USER';
export const UPDATE_ERRORS = 'UPDATE_ERRORS';
export const INCREMENT_POINTS = 'INCREMENT_POINTS';
export const INCREMENT_WORDS = 'INCREMENT_WORDS';
type Error = {
code: number;
message: string;
};
type FetchUserAction = {
type: typeof FETCH_USER;
payload: User;
};
type UpdateErrorsAction = {
type: typeof UPDATE_ERRORS;
payload: Error[];
};
type IncrementPointsAction = {
type: typeof INCREMENT_POINTS;
payload: number;
};
type IncrementWordsActions = {
type: typeof INCREMENT_WORDS;
};
// ? Typescript is able to infer the correct type in the Union Type below
export type useUserActionTypes =
| FetchUserAction
| UpdateErrorsAction
| IncrementPointsAction
| IncrementWordsActions;
export type ReduxStore = {
alert: any;
user: User;
};
const useUser = (): useUserActionTypes => {
const userData: User = useSelector((state: ReduxStore) => state.user);
const totalPoints: number = useSelector(
(state: ReduxStore) => state.user.points
);
const totalWords: number = useSelector(
(state: ReduxStore) => state.user.words
);
const dispatch = useDispatch();
const fetchUser = async (): Promise<FetchUserAction | UpdateErrorsAction> => {
try {
const response = await axios.get(
'http://localhost:5000/api/v1/users/WhpHq4qWFdzlhlx2ztqD'
);
const user = response.data;
return dispatch({
type: FETCH_USER,
payload: user,
});
} catch (error) {
return dispatch({
type: UPDATE_ERRORS,
payload: [
{
code: 500,
message: error.message,
},
],
});
}
};
const incrementPoints = (amount: number): useUserActionTypes => {
return dispatch({
type: INCREMENT_POINTS,
payload: amount,
});
};
const incrementWords = (): useUserActionTypes => {
return dispatch({
type: INCREMENT_WORDS,
});
};
return {
userData,
totalPoints,
totalWords,
fetchUser,
incrementPoints,
incrementWords,
};
};
export default useUser;
在我尝试使用选择器的页面上:
fetchUser()
返回“ any”类型...可能与上述相同?谢谢您的帮助,尝试将所有内容与打字稿正确连接绝对是一件很有趣的事情,但目前我有点迷茫。
答案 0 :(得分:2)
问题在于您错误地键入了useUser
,根据您的代码,正确的返回类型将是:
{
userData: User;
totalPoints: number;
totalWords: number;
fetchUser(): Promise<FetchUserAction | UpdateErrorsAction>;
incrementPoints(amount: number): useUserActionTypes;
incrementWords(): useUserActionTypes;
}