为钩子设置React / Redux打字稿

时间:2020-08-27 20:53:30

标签: javascript reactjs typescript redux react-hooks

我一直在网上寻找不同的资源,试图找到适合我所拥有的解决方案,到目前为止,我认为我有点在破坏我的打字稿集成。我希望在正确设置钩子类型方面有所帮助。

我有一个useUser()钩子,该钩子将动作分派给我的reducer,并且还从我的商店返回选择器。我已经取得了一些进步,但是我开始有点烦恼了。

挂钩:useUser.ts

  • 我不确定我可以把什么作为该钩子的回报。我尝试放置useUserActionTypes,但我认为这没有什么区别,尤其是因为除了返回对象(userData)或数字之外,我没有返回任何其他东西 (totalPointstotalWords)。
  • 我不认为我应该“退回”我的派遣单,但是这使打字稿的烦恼减少了。
  • 例如,我也可以只键入“ Dog”之类的内容,而不是将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;

enter image description here


在我尝试使用选择器的页面上:

  • 我以为这些都在我的钩子中了,我为这些常量分配了类型。
  • fetchUser()返回“ any”类型...可能与上述相同?

enter image description here

enter image description here

谢谢您的帮助,尝试将所有内容与打字稿正确连接绝对是一件很有趣的事情,但目前我有点迷茫。

1 个答案:

答案 0 :(得分:2)

问题在于您错误地键入了useUser,根据您的代码,正确的返回类型将是:

{
    userData: User;
    totalPoints: number;
    totalWords: number;
    fetchUser(): Promise<FetchUserAction | UpdateErrorsAction>;
    incrementPoints(amount: number): useUserActionTypes;
    incrementWords(): useUserActionTypes;
}

Playground

相关问题