Home > Blockchain >  How can I set the types for a destructured value
How can I set the types for a destructured value

Time:10-13

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

CodePudding user response:

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

CodePudding user response:

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

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

where someType is the appropriate type

  • Related