'How to set the response type using axios with Javascript and JSDocs?

My API has a response as follows:

{
  "foo": "bar",
  "bar": "foo"
}

So I've created the response type using JSDocs as follows:

/**
 * typedef {Object} AwesomeAPIResponse
 * property {string} foo
 * property {string} bar
 */

So, I'm calling my API using Axios with a post request:

const axios = require('axios').default

const someFunction = async () => {
  const result = await axios.post(MY_API_URL, data, {
    headers: { ... },
    method: 'post'
  })

  return result
}

So far, so good, but the type of my response is AxiosResponse<any>, and I want it to be AxiosResponse<AwesomeAPIResponse>. I know I can achieve this by using TypeScript generics, but I'm not allowed to use TS and I don't want to return any as type. Is it possible to do something like this?



Solution 1:[1]

JSDoc is just used for type hinting for the IDE it can't be used in the way you're trying to.

The only way to return a "AwesomeAPIResponse" is by creating a class with that definition

class AwesomeAPIResponse {
    constructor(foo, bar) {
        this.foo = foo;
        this.bar = bar;
    }
}

and then returning a new instance of it based on the result

const someFunction = async () => {
  const result = await axios.post(MY_API_URL, data, {
    headers: { ... },
    method: 'post'
  })
  const {foo, bar} = result;

  return new AwesomeAPIRespone(foo, bar);
}

Solution 2:[2]

This works in VSCode.

/**
 * @typedef {Object} Comment
 * @property {number} id The PK.
 * @property {number} postId The FK of the post the comment is related to.
 * @property {string} body The comment's content.
 */

/**
 * @typedef {import("axios").AxiosResponse<Comment>} CommentResponse
 */

/**
 *
 * @param {number} id The primary key of the comment to find.
 * @returns {Promise<CommentResponse>}
 */
async function findCommentById(id) {
  return axios.get(`https://jsonplaceholder.typicode.com/comments/${id}`);
}

const commentRes = await findCommentById(5);
console.log(commentRes.data.body);

axios response data intellisense

axios response intellisense

Warning: Trying to avoid having to import each time by doing this did not work: @typedef {import("axios").AxiosResponse} AxiosRes -> AxiosRes<YourDataType>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TheBritishAreComing
Solution 2