Type Check an Http Response using the Angular HttpClient and TypeScript

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 6 years ago

When we invoke our backend API, we retrieve some well defined data object, such as a Person. By using TypeScript we can define the Type of such a data object and also provide this type to the Angular HttpClient. As a consequence, our Http request gets “typed” and we get an instance of a Person type.

In this example here, I am using here a people service, which internally uses the HTTP client to fetch some data which I directly print out here on the UI. As you can see, this is the structure of our data. However, if we work within here, our subscribe callback, we don't get any auto-completion from TypeScript, because it cannot infer the kind of data which we are retrieving.

The point here is, if we go into people service, we see that we get here an observable of type object, which is obviously not of type person. Let's quickly go here and define an interface person, which models our simple data structure.

What we can do now is to first of all return an observable of type person, but more interestingly, the new HTTP client introduced in Angular 4.3.1, which resides here in this Angular common HTTP package, has now here a type specifier where we can pass in the person interface which we just created.

Now in this way, if we go back to our app component, and we again try here to invoke that data object, we can see that TypeScript shows us that this of type person, and we can then access all the properties which are defined in this type.

Obviously, the data call itself still works as we would expect. This is a really powerful way of typing your response and catch errors early on in your process.