You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 GitHubRepoData interface to get autocompletion and catch typos (like misspelling stargazers_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 const instead of var for immutability, and template literals for cleaner console logs.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:00:21