To use Web APIs for making HTTP requests in a local TypeScript project, you need to follow a similar approach to using them in JavaScript, with the additional step of ensuring that TypeScript is aware of the types involved.
Let's assume you mean to perform HTTP requests in a Node.js environment using TypeScript. Since fetch is not a built-in Node.js API, here is how you can use node-fetch or axios (both of which are compatible with TypeScript) to make HTTP requests.
Option 1: Using node-fetch with TypeScript
- Install
node-fetch:
npm install node-fetch
- You may also need to install the types for
node-fetch if they are not included:
npm install @types/node-fetch --save-dev
- Use
node-fetch in your TypeScript file:
import fetch from 'node-fetch';
// Now you can use fetch() as you would in the browser
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Option 2: Using axios with TypeScript
axios already includes TypeScript definitions, so there is no need to install additional types.
- Install
axios:
npm install axios
- Use
axios in your TypeScript file:
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error:', error);
});
Configuring TypeScript
Make sure your tsconfig.json file is properly set up to compile your TypeScript code into JavaScript. Here's a simple example of a tsconfig.json:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
The "esModuleInterop" option allows you to use import statements more easily, especially when importing default exports from CommonJS modules.
Now, you can compile your TypeScript code using the TypeScript compiler (tsc). If your TypeScript files are in a src directory and you are using the above tsconfig.json, you can simply run:
npx tsc
This will compile your TypeScript code to JavaScript according to the options specified in your tsconfig.json file. After that, you can run your compiled JavaScript code using Node.js:
node dist/your-compiled-file.js
Remember that the dist/your-compiled-file.js path may vary depending on the settings in your tsconfig.json file, where your-compiled-file.js is the JavaScript output from the TypeScript compilation of your original TypeScript file.