【问题标题】:Typing Axios interceptor (axios.create) response typescript definitions键入 Axios 拦截器 (axios.create) 响应打字稿定义
【发布时间】:2022-01-18 16:53:19
【问题描述】:

我目前正在开发一个 react typescript 应用程序,并且正在尝试正确键入我的 axios 拦截器。我似乎无法弄清楚如何破解这些类型。

TL;DR 问题:TS 无法正确识别我的 axios 拦截器响应配置类型。

我的代码 --拦截器创建

const client = axios.create({
  baseURL: apiURL
});

export const api = < T,
  D > ({ ...options
  }: AxiosRequestConfig < D > ) => {
    const token = getToken();

    client.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    const onSuccess = (response: AxiosResponse < T > ) => response;
    const onError = (error: Error | AxiosError) => {
      if (axios.isAxiosError(error)) {
        if (error.response ? .status === 401) {
          logout();
          window.location.assign(window.location.href);
          return Promise.reject({
            message: 'Please re-authenticate.'
          });
        } else {
          return error;
        }
      }
      return error;
    };

    return client(options).then(onSuccess).catch(onError);
  };

export default api;

使用 Axios 实例

// I created a generic shown in the previous code used to define the response type
api < USER > ({
    url: 'auth/me'
  })
  .then((response) => { // Error | AxiosResponse<User>
    // have to add typeguards for TS not to complain that it COULD be type ERROR
    if (!(response instanceof Error)) {
      setUser(response.data);
      setStatus('success');
    }
  })
  // here, TS doesn't know what this is at all ? err: any 
  .catch((err) => { //err: any
    setError(err);
    setStatus('rejected');
  });

问题

正如您从我的代码 cmets 中看到的那样,TS 强制我键入保护类型“成功”场景(意味着请求没有失败),以确保它不是错误,这很烦人,因为我已经定义了什么类型应该是onSuccess。此外,我的 .catch 方法中没有任何类型定义。

我知道 Promise 可以在 .then.catch 中返回错误,但是为什么我不能让 TS 弄清楚当我明确通过它时我将使用 .catch 来处理错误正确的打字?

感谢您的所有帮助!我真的在这里挣扎。关于 Axios TS 的讨论很多,但我似乎找不到这个。

有帮助的讨论:https://github.com/axios/axios/issues/4176

【问题讨论】:

标签: javascript reactjs angular typescript axios


【解决方案1】:

您不应该在 API 函数中返回错误 return error;,这就是 TypeScript 强制您检查 then 子句中的类型的原因,因为它期望错误作为可能的返回类型。 Catch 子句仅在抛出错误 throw error 或当 Promise 被拒绝 Promise.reject 时运行。

【讨论】:

  • 这太不可思议了!你是绝对正确的!奇怪的是,即使我不再需要对我的.then 响应进行类型保护,我的.catch 语句中仍然没有任何类型安全性,它默认为err: any。而且,奇怪的是,它甚至没有让我对错误进行打字。关于为什么会这样的任何想法?谢谢你一百万倍!
  • Catch 子句错误始终默认为any,除非配置为默认为unknown (typescriptlang.org/tsconfig#useUnknownInCatchVariables)。您也可以将变量显式键入为未知catch(err: unknown) {。我不明白你的意思是它不允许你在 catch 子句中键入错误。
  • 您可能会觉得这很有帮助:stackoverflow.com/questions/69021040/…
  • 感谢@Michael Boñon 的解释!
猜你喜欢
  • 2018-09-27
  • 2022-01-25
  • 1970-01-01
  • 2020-09-25
  • 2020-11-21
  • 1970-01-01
  • 1970-01-01
  • 2020-10-22
相关资源
最近更新 更多