fetch json data from an api in typescript

To fetch JSON data from an API using TypeScript, we can make use of the fetch function that is available in modern browsers. Here's an example of how to do it:

index.ts
fetch('https://api.example.com/data.json')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });
178 chars
9 lines

In this example, we first call the fetch function with the URL of the API as its argument. The fetch function returns a Promise that resolves to a Response object.

We then call the json method on the Response object, which returns another Promise that resolves to the actual JSON data. We finally log the JSON data to the console in the then method of this Promise.

If there's an error in fetching the data or parsing it as JSON, we catch the error in the catch method and log it to the console instead.

This code block assumes that you have set the appropriate CORS headers on the API server if the requests are coming from another domain.

gistlibby LogSnag