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 5 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.

egghead
egghead
~ 2 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today