This video is available to students only

Giving Types to Axios

In this lesson, we're assign types to Axios response

Giving types to Axios#

What's the point of using Typescript if we can't provide type safety to our response? Without wasting any time, let's directly jump to fix that.

If you look at the responseBody variable, this is the only variable we're going to use for storing the response, so we can't give that any specific type and it has to be generic which can fit all our use cases.

Ideally, to give type, we need to create a structure for it which is called model or entity. Since we're going to receive course list here, we need to create a Course model which will have all the properties we're going to receive or expect.

Inside the src directory, let's create a new directory called models and create a new file here which will be called course.ts. We need to write an interface which will be called Course. Inside the curly brackets, we just need to write the properties that we've written inside our backend. For now, we have id which is of type string, title which is again string, price which is of type number, instructor which is of type string, image again which is of type string and rating which is of type number. That's it. We can add export to the beginning.

Start a new discussion. All notification go to the author.