Using the fetch API for network requests in TypeScript is a common practice, as it allows you to asynchronously retrieve resources from the network. Below are the steps and examples for using fetch in TypeScript:
1. Basic Usage
First, you can directly use the fetch function to send a GET request and retrieve data. For example, we request JSON data from an API:
typescriptfetch('https://api.example.com/data') .then(response => { // Verify that the response status code is 200 if (!response.ok) { throw new Error('Network response was not ok ' + response.statusText); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('There was a problem with your fetch operation:', error));
2. Using in Async Functions
To make the code more readable and manageable, you can use fetch within an async function, allowing you to use the async and await keywords:
typescriptasync function fetchData() { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new Error('Network response was not ok'); } const data = await response.json(); console.log(data); } catch (error) { console.error('There was a problem with your fetch operation:', error); } } fetchData();
3. Adding Types
In TypeScript, you can define an interface to describe the expected data structure, which helps improve code readability and robustness:
typescriptinterface Data { id: number; name: string; } async function fetchDataTyped(): Promise<Data> { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new Error('Network response was not ok'); } const data: Data = await response.json(); console.log(data); return data; } catch (error) { console.error('There was a problem with your fetch operation:', error); throw error; } } fetchDataTyped();
4. Handling POST Requests
To send a POST request using fetch, you need to specify the request method and the request body:
typescriptasync function postData(url: string, data: Data): Promise<Data> { try { const response = await fetch(url, { method: 'POST', // Specify the request method headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), // Convert the JavaScript object to a JSON string }); if (!response.ok) { throw new Error('Network response was not ok'); } const responseData: Data = await response.json(); console.log(responseData); return responseData; } catch (error) { console.error('There was an error posting the data:', error); throw error; } } const myData = { id: 123, name: 'Example' }; postData('https://api.example.com/data', myData);
When using fetch, ensure you handle various potential error cases, including network errors and server errors. Additionally, properly utilizing TypeScript's type system can help ensure the accuracy of data processing and the robustness of your code.