Using Generics With Observables

Learn how we can take advantage of TypeScript to help us document our request.

We'll cover the following

Services are classes where we can outsource requests. They’re great because they’re reusable, and we can import them in any number of components.

One of the main issues we face with services is not knowing what to expect when we make a request. The only way we can know is if we look at the documentation of the API. This means that we’ll have to refer to the documentation whenever we want to use the API.

At first, it’s not much of an issue. However, as our app scales, it can become cumbersome to have to go back and forth. One way we can combat this issue is by using TypeScript’s interface feature. An interface is a way to create a new type.

Defining an interface

We’ll define the interface in the cocktail.service.ts file because that’s where the request is being initiated. We’ll add the interface above the class.

interface CocktailResponse {
  drinks: {
    strDrink: string;
    strInstructions: string;
  }[]
}

We’re calling the interface CocktailResponse. The interface will describe the response from the request. We know that the request will send back an array of objects under the drinks property. We can annotate an array of objects by adding a pair of square brackets after the closing curly bracket.

In each object, we can expect two properties: strDrink and strInstructions. Both of their types are of string. There is much more data that will come from the request, but we’re only adding the ones we’ll be using in our application. We’re not required to define every property in the object.

Using generics

Generics are another feature of TypeScript. They can be used to dynamically set types in a class or function. Observables can be assigned a generic to help TypeScript understand the kind of response it can expect. We can apply a generic to the http.get() method, as shown here:

Get hands-on with 1400+ tech skills courses.