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

在TypeScript类中如何为Octokit REST API调用生成正确响应类型?

解决Octokit REST API响应类型生成与运行时token冲突问题

问题背景

你在TypeScript中开发自定义GitHub Action时,为了获取Octokit pulls.get 接口的响应类型,通过创建空token的octokit实例推导类型,但这会导致运行时报错;同时你需要保留方法的显式返回类型以符合lint规则,无法将类型定义在方法内部。

核心解决方案:纯类型层面推导,避免运行时实例化

不需要创建实际的octokit实例来推导类型,直接通过@octokit/types或@octokit/rest提供的类型定义获取接口响应类型,完全规避空token的运行时问题。

方案1:直接使用预定义的Octokit接口类型

从@octokit/rest导入Octokit类型,直接引用其rest.pulls.get的类型进行推导:

import { debug } from '@actions/core';
import { getOctokit } from '@actions/github';
import type { Octokit } from '@octokit/rest';
import type { GetResponseDataTypeFromEndpointMethod } from '@octokit/types';

// 纯类型推导,无运行时实例
type Pull = GetResponseDataTypeFromEndpointMethod<Octokit['rest']['pulls']['get']>;

export class GitHubService {
  private readonly octokit;

  constructor(gitHubToken: string) {
    this.octokit = getOctokit(gitHubToken);
  }

  async handlePullRequestChange(
    repositoryOwner: string,
    repositoryName: string,
    pullRequestNumber: number
  ): Promise<Pull> {
    // 注意:pulls.get返回单个PR,无需使用paginate
    const pull = await this.octokit.rest.pulls.get({
      owner: repositoryOwner,
      repo: repositoryName,
      pull_number: pullRequestNumber
    });

    debug(`Pull request ${pullRequestNumber} includes the following body: ${JSON.stringify(pull.data)}`);
    // 返回data字段,Octokit响应包含data、status等属性,data才是实际PR数据
    return pull.data;
  }
}

方案2:通过ReturnType推导Octokit实例类型

如果不想导入完整的Octokit类型,可以通过ReturnType获取getOctokit的返回类型,再推导接口类型:

import { debug } from '@actions/core';
import { getOctokit } from '@actions/github';
import type { GetResponseDataTypeFromEndpointMethod } from '@octokit/types';

// 推导getOctokit返回的实例类型
type OctokitInstance = ReturnType<typeof getOctokit>;
// 基于实例类型推导pulls.get的响应类型
type Pull = GetResponseDataTypeFromEndpointMethod<OctokitInstance['rest']['pulls']['get']>;

// 后续类代码与方案1一致

额外修正点

你原代码中使用octokit.paginate调用pulls.get是错误的:paginate用于处理返回列表的接口(如pulls.list),而pulls.get返回单个PR对象。直接调用this.octokit.rest.pulls.get即可,且需要返回pull.data(Octokit响应对象的data字段才是实际的PR数据)。


内容的提问来源于stack exchange,提问作者Sayak Mukhopadhyay

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 03:10:31