reactjs 类型“{}"无法分配给类型”AxiosRequestHeaders“

wfauudbj  于 2023-01-30  发布在  React
关注(0)|答案(2)|浏览(1671)
type here

我正在使用一个带有typescript的react应用程序,但AxiosResquestHeader出现错误,它总是获取不可分配的类型。我希望从localStorage获取登录用户的当前令牌。这是我的AuthHeaders.ts

export default function authHeader(): AxiosRequestHeaders {
  type userToken = {
  accessToken: string;
};
  const localstorageUser = localStorage.getItem("user");
  if (!localstorageUser) {
    return {};
  }
  const user = JSON.parse(localstorageUser);
  if (user && user.token) {
    return { Authorization: `Token ${user.token}` };
  }
  return {};

}

并从AuthContext.ts调用,如下所示

export const AuthContextProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const navigate = useNavigate();
  const [user, setUser] = useState(() => AuthService.getCurrentUser());

  async function login(email: string, password: string) {
    const data = await AuthService.login(email, password);
    setUser(data);
    return data;
  }

  function logout() {
    AuthService.logout();
    setUser(null);
    navigate("/login");
  }

  // axios instance for making requests
  const authAxios = axios.create();

  // request interceptor for adding token
  authAxios.interceptors.request.use((config) => {
    // add token to request headers
   ** config.headers = authHeader();**
    return config;
  });

这是我得到的错误:

ERROR in src/services/AuthHeaders.ts:14:5

TS2322: Type '{ Authorization: string; }' is not assignable to type 'AxiosRequestHeaders'.
  Type '{ Authorization: string; }' is missing the following properties from type 'AxiosHeaders': set, get, has, delete, and 23 more.
    12 |   const user = JSON.parse(localstorageUser);
    13 |   if (user && user.token) {
  > 14 |     return { Authorization: `Token ${user.token}` };
       |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    15 |     // throw new Error('User Token Found');
    16 |   }
    17 |   // return {};

ERROR in src/services/AuthHeaders.ts:14:5

TS2322: Type '{ Authorization: string; }' is not assignable to type 'AxiosRequestHeaders'.
  Type '{ Authorization: string; }' is missing the following properties from type 'AxiosHeaders': set, get, has, delete, and 23 more.
    12 |   const user = JSON.parse(localstorageUser);
    13 |   if (user && user.token) {
  > 14 |     return { Authorization: `Token ${user.token}` };
       |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    15 |     // throw new Error('User Token Found');
    16 |   }
    17 |   // return {};

当我注解掉AuthHeaders.ts中的返回方法并将其替换为throw new Error()时,程序似乎编译没有任何问题,但当然,逻辑是不正确的。
我对typescript和react的概念有点陌生,但我确信这可以与typescript返回类型一起使用。无论如何,我真的需要你的帮助。谢谢

lb3vh1jj

lb3vh1jj1#

您可能希望使用RawAxiosRequestHeaders而不是AxiosRequestHeaders
AxiosRequestHeaders是从AxiosHeaders继承的类,不能仅从对象({})示例化。
另一方面,RawAxiosRequestHeaders只是一个接口,可能适合您在这里尝试实现的目标。

hs1rzwqc

hs1rzwqc2#

我看到您只是返回一个包含授权令牌的对象,因此authHeader的返回类型不一定是AxiosRequestHeaders
您可以在函数的返回类型中使用它。

type userToken = {
  accessToken: string;
}

export default function authHeader(): {Authorization: string} | {} {
}

type userToken = {
  accessToken: string;
};

export default function authHeader(): {Authorization: string} | {} {
  const localstorageUser = localStorage.getItem("user");
  const user = JSON.parse(localstorageUser);
  if (user && user.token) {
    return { Authorization: `Token ${user.token}` };
  }
  return {};
}

相关问题