How to add types for Axios response with React and TypeScript?

Sometimes, we want to add types for Axios response with React and TypeScript.

In this article, we’ll look at how to add types for Axios response with React and TypeScript.

How to add types for Axios response with React and TypeScript?

To add types for Axios response with React and TypeScript, we can set the type when we call an axios method.

For instance, we write

interface User {
  id: number;
  firstName: string;
}

to define the User interface.

Then we call axios.get and set response body type to a User array by writing

const { data } = await axios.get<User[]>("http://localhost:8080/admin/users");

in an async function.

User[] is the type of the response body return by the promise of axios.get.

Conclusion

To add types for Axios response with React and TypeScript, we can set the type when we call an axios method.