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.ts218 chars10 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.ts184 chars7 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