Making a Fetch Request with TypeScript

Isabella Chen
Oct 7, 2018 · 2 min read

In TypeScript, you have to be explicit about what your functions return. A source of confusion for me in the past has been this — what if you have a method that makes a request to an API that isn’t yours? How should you specify the return value?

A common scenario for such methods would be in a Service class. In this example, I’ll create a service that fetches a list of movies from some external API.

class Movie {
title: string;
id: number;
constructor(title: string, id: number) {
this.title = title;
this.id = id;
}
}
class MovieService {
getMovies(genre: string): Promise<Movie[]> {
return fetch(`https://www.movies.com/${genre}`)
.then(res => res.json())
}
}

Suppose the api returns you an array of objects, each with 4 properties on them, {title, id, rating, video}.

What happens when we try to log the return value of the fetch?

apiClient.getMovies('sci-fi').then(movies => console.log(movies[0].video));

Typescript will complain that property .video does not exist on type Movie. Even if property .video did exist on each object in the array sent in by the API, TypeScript will still complain because it doesn’t care what the API returns, it only cares what you say the method getMovies(genre: string)` will return.

Currently our method is not written correctly. We specified that getMovies() will return an array of type Movie, with each Movie instance having two properties, title and id. To make sure that we return the correct values, we need to format the response coming in from the API.

function formatMovie(movie: any): Movie {
return { title: movie.title, id: movie.id };
}
class MovieService {
getMovies(genre: string): Promise<Movie[]> {
return fetch(`https://www.movies.com/${genre}`)
.then(res => res.json())
.then(res => res.map((movie: any) => formatMovie(movie))
}
}
const apiClient = new MovieService();//log list of movies
apiClient.getMovies('sci-fi').then(movies => console.log(movies));

I hope this little example will find you if you’re confused abouthow to use fetch with Typescript!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade