call an api in typescript

To call an API in TypeScript, we can use the fetch API that makes HTTP requests. It returns a promise, so we can either use async/await or then/catch syntax.

Here's an example of using fetch with async/await:

index.ts
async function fetchData() {
  try {
    const response = await fetch('https://example.com/api/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}
218 chars
10 lines

In the above code, we create an async function and use the await keyword to wait for the response of the fetch call. We then extract the JSON data from the response using the json method, again using await. Finally, we log the data to the console.

If we want to use then/catch syntax, we can do something like this:

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

In the code above, we use the then method to handle the response and data, and the catch method to handle errors.

Either way, we can easily call APIs in TypeScript using the fetch API.

gistlibby LogSnag