bonum_cete
bonum_cete

Reputation: 4962

How can I set the types for a destructured value

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

Upvotes: 1

Views: 669

Answers (2)

jsonderulo
jsonderulo

Reputation: 1464

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

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

where someType is the appropriate type

Upvotes: 0

hoangdv
hoangdv

Reputation: 16127

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 }
  })

Upvotes: 3

Related Questions