0

I have an axios POST like this:

axios
      .post(url, payload)
      .then((res) => {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
        const { someObject } = res.data;
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
        const { someString } = res.data;
...

Currently I have to disable the eslint for those lines. How can I avoid this?

I did try creating interfaces and getting res and res.data as AxiosResponse, but no luck

bonum_cete
  • 4,730
  • 6
  • 32
  • 56
  • Try `generic` See [here](https://stackoverflow.com/questions/62217642/react-and-typescript-which-types-for-axios-response) – awran5 Oct 13 '21 at 01:43

2 Answers2

3

Let's define the request response type. axios.post is a generic function, then you can define the response of the post request:

interface IPostResponse {
  someObject: { name: string };
  otherField: number;
}

axios.post<IPostResponse>(url, payload)
  .then(res => {
    // res.data is a IPostResponse
    const { someObject } = res.data; // someObject is a { name: string }
  })
hoangdv
  • 15,138
  • 4
  • 27
  • 48
0

Generally, you can annotate the type for a desctructered object like so:

const { someString }: {someString: someType} = res.data;

where someType is the appropriate type

jsonderulo
  • 1,241
  • 1
  • 12
  • 18