【问题标题】:Why am I losing typing of a parameter with spread operator?为什么我会丢失使用扩展运算符输入的参数?
【发布时间】:2019-11-27 05:43:54
【问题描述】:

通过使用 Octokit 包,我想列出所有拉取请求 (client.pulls.list)。

我有一个 GitHubClient(Octokit 的包装器)和 GitHubService(GitHubClient 的包装器)。 GitHubService 有一个 options 参数,使用带有 perPage?: number; 属性的接口,而 GitHubClient 接受带有属性 per_page?: number; 的接口的选项

在下面的代码中,我在 GitHubClient 类中丢失了 options 的类型检查。

我做错了什么以及如何正确设置选项类型?

import Octokit from '@octokit/rest';

interface PaginationParams {
  page?: number;

  // camelcase
  perPage?: number;
}

interface GitHubPaginationParams {
  page?: number;

  // underscored
  per_page?: number;
}

class GitHubClient {
  private client: Octokit;

  constructor() {
    this.client = new Octokit();
  }

  getPullRequests(options: PaginationParams) {
    // lost typings of "options" with spread operator (no typescript error)
    return this.client.pulls.list({ owner: 'octokit', repo: 'hello-world', state: 'open', ...options });

    // this works (typescript error)
    // return this.client.pulls.list({ owner: 'octokit', repo: 'hello-world', state: 'open', page: options.page, per_page: options.per_page });

    // this works
    // return this.client.pulls.list({ owner: 'octokit', repo: 'hello-world', state: 'open', page: options.page, per_page: options.perPage });
  }
}

class GitHubService {
  private ghClient: GitHubClient;

  constructor() {
    this.ghClient = new GitHubClient();
  }

  async getPullRequests(options: GitHubPaginationParams) {
    return this.ghClient.getPullRequests(options);
  }
}

我希望 typescript 会引发错误,因为 GitHubService 的 options 接口与 GitHubClient 接口中的 options 不同。

【问题讨论】:

标签: javascript typescript api github octokit


【解决方案1】:

您的所有字段(在两个接口中)都是可选的 - 这意味着即使是空对象也可以实现这些接口。只要您标记了必填字段,预期的行为就会起作用。

目前你有下一个:

interface PaginationParams {
  page?: number;

  // camelcase
  perPage?: number;
}

interface GitHubPaginationParams {
  page?: number;

  // underscored
  per_page?: number;
}

// cause none of the fields is required
var x:PaginationParams = {};
var y:GitHubPaginationParams = x;

如果您删除 page 附近的 ? - 类型将与该字段兼容。如果您为 per_page/perPage 删除它 - 您可能会收到预期错误,或者您必须同时提供这两个属性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-19
    • 2019-09-23
    • 2020-01-27
    • 2017-10-11
    • 2021-12-23
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多