Tìm kiếm trang web

javascript - Kiểu phản hồi của TypeScript và Axios


Tôi đang sử dụng axios để giao tiếp với các API của mình, và tôi đóng gói nó bằng một lớp HTTClient để tránh phụ thuộc nhiều vào nó:

import axios, { AxiosInstance } from 'axios';
import https from 'https';
import { stringify } from 'qs';

class HttpClient {
  private static instance: AxiosInstance;

  constructor() {
    const axiosInstance = axios.create({
      baseURL: process.env.ENDPOINT_API,
      httpsAgent: new https.Agent({
        rejectUnauthorized: false,
      }),
    });

    axiosInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    axiosInstance.defaults.paramsSerializer = this.paramsSerializer;
    axiosInstance.defaults.withCredentials = true;

    axiosInstance.interceptors.response.use((response) => response.data);

    HttpClient.instance = axiosInstance;
  }

  public static getInstance = () => {
    if (!HttpClient.instance) new HttpClient();

    return HttpClient.instance;
  };

  private paramsSerializer = (params) => stringify(params, { arrayFormat: 'repeat' });
}

export default HttpClient.getInstance();

Như bạn sẽ nhận thấy, khi tôi làm

axiosInstance.interceptors.response.use((response) => response.data);

Tôi đang trả về nội dung của data. Vấn đề là bây giờ kiểu của phản hồi bị sai.

interface TypedResponse {
  name: string
}

const response = await HttpClient.put<TypedResponse>(`/`);
const response.name // Property 'name' does not exist on type 'TypedResponse'.ts(2339)

TypeScript đang nghĩ rằng name nằm trong data, như sau:

// Response
{
  data: {
    name: string;
  }
}

Điều này tất nhiên là sai, vì tôi không còn trả về data nữa:

// Response
{
  name: string
}

Làm thế nào để tôi thay đổi kiểu phản hồi mặc định của axios trong lớp của mình?