如何在TypeScript中实现Protractor测试的POST请求(迁移request模块)
Got it, let's convert that JavaScript Protractor request logic to clean, type-safe TypeScript! Here's a step-by-step breakdown and working code:
First, set up dependencies
Since TypeScript relies on type definitions, make sure you have both the request package and its types installed:
npm install request @types/request --save-dev
(Note: request is officially deprecated now—if you can switch, I'd recommend using modern alternatives like axios or Node.js's built-in fetch later on, but let's first convert your original code as requested.)
Converted TypeScript Code
import * as request from 'request'; // Define an interface to enforce type safety for the GitHub API response interface GitHubRepoData { stargazers_count: number; forks_count: number; // Add any other fields you need from the API here } // Type-annotated options object const requestOptions: request.Options = { url: 'https://api.github.com/repos/request/request', headers: { 'User-Agent': 'request' } }; // Callback with explicit type annotations for all parameters const handleResponse = ( error: Error | null, response: request.Response, body: string ): void => { if (!error && response.statusCode === 200) { // Parse the response body into our typed interface const repoInfo: GitHubRepoData = JSON.parse(body); console.log("Inside function"); console.log(`${repoInfo.stargazers_count} Stars`); console.log(`${repoInfo.forks_count} Forks`); } }; // Execute the request request(requestOptions, handleResponse);
Key improvements over the original JS code:
- Type safety: We added the
GitHubRepoDatainterface to get autocompletion and catch typos (like misspellingstargazers_count) at compile time. - Explicit types: All variables and function parameters have clear type annotations, making the code easier to read and maintain.
- Modern syntax: Used
constinstead ofvarfor immutability, and template literals for cleaner console logs.
Bonus: Modern Alternative with Axios (Recommended)
Since request is deprecated, here's a cleaner, promise-based version using axios (which has built-in TypeScript support):
npm install axios --save-dev
import axios from 'axios'; interface GitHubRepoData { stargazers_count: number; forks_count: number; } async function fetchRepoStats(): Promise<void> { try { // Use axios's generic get method to directly type the response data const response = await axios.get<GitHubRepoData>( 'https://api.github.com/repos/request/request', { headers: { 'User-Agent': 'request' } } ); const repoInfo = response.data; console.log("Inside function"); console.log(`${repoInfo.stargazers_count} Stars`); console.log(`${repoInfo.forks_count} Forks`); } catch (error) { console.error('Failed to fetch repo stats:', error); } } // Run the async function fetchRepoStats();
This uses async/await for cleaner asynchronous code, eliminates callback hell, and has robust error handling.
内容的提问来源于stack exchange,提问作者Praveen

