You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中结合JSDocs为Axios请求设置自定义响应类型

方案1:仅需要静态类型提示(无需修改业务逻辑)

你可以直接通过JSDoc注解实现类型标注,不需要引入TypeScript,VSCode、WebStorm等主流IDE都默认支持该能力:

  1. 首先补全你现有的JSDoc类型定义的注解前缀:
/**
 * @typedef {Object} AwesomeAPIResponse
 * @property {string} foo
 * @property {string} bar
 */
  1. 给请求函数加类型注解,有两种常用写法:
  • 方式一:给返回值变量直接标注类型
const axios = require('axios').default

const someFunction = async () => {
  /** @type {import('axios').AxiosResponse<AwesomeAPIResponse>} */
  const result = await axios.post(MY_API_URL, data, {
    headers: { /* 你的请求头配置 */ }
  })
  // 此时IDE可自动识别result.data为AwesomeAPIResponse类型,无any提示
  return result
}
  • 方式二:给函数标注返回值类型,调用该函数的位置也能自动获得类型提示
/**
 * @returns {Promise<import('axios').AxiosResponse<AwesomeAPIResponse>>}
 */
const someFunction = async () => {
  const result = await axios.post(MY_API_URL, data, {
    headers: { /* 你的请求头配置 */ }
  })
  return result
}

如果想要获得更完整的Axios类型提示,可以将@types/axios安装为开发依赖,IDE会自动读取类型定义,不会影响生产代码运行。

方案2:需要运行时校验类型

如果需要在运行时也确保API返回符合预期结构,可以额外加一层类型校验:

/**
 * @param {unknown} data
 * @returns {data is AwesomeAPIResponse}
 */
function isAwesomeAPIResponse(data) {
  return (
    typeof data === 'object' &&
    data !== null &&
    typeof data.foo === 'string' &&
    typeof data.bar === 'string'
  )
}

const someFunction = async () => {
  const result = await axios.post(MY_API_URL, data, {
    headers: { /* 你的请求头配置 */ }
  })
  // 运行时校验返回格式
  if (!isAwesomeAPIResponse(result.data)) {
    throw new Error('API返回格式不符合预期')
  }
  /** @type {import('axios').AxiosResponse<AwesomeAPIResponse>} */
  const typedResult = result
  return typedResult
}

这样既能获得静态类型提示,也能在API返回异常时提前捕获问题。

内容的提问来源于stack exchange,提问作者Anthony Luzquiños

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 03:27:05