打字稿对象在参数中休息打字

Typescript object rest typings in argument

我对 Typescript 有点陌生,我可以对 90% 的代码库进行打字。但是当涉及到 rest/spread 操作符时,我绝对不知所措。我今天在我们的代码中偶然发现了这个(我没有写这个)但我确实发现它不起作用:

interface searchClient {
  searchForValues({
    name,
    query,
    ...qp,
  }: {
    name: string;
    query: string;
    qp: QpInterface;  //???this part doesn't work
  }): Promise<any>;
 }

interface QpInterface {
  page?: number;
  hits?: number;
  attributes?: string;
}

它不起作用,因为 qp 正在指定键入中的键名,而我要键入的是 ...qp 部分。 ...qp 中的每个 key/value 对都由 QpInterface 输入。

这是一个示例函数调用:

this.searchClient.searchForValues({
  name: 'title',
  query: 'little sheep',
  page: 5,
  hits: 2
});

我在文档中找不到太多相关信息。我试过输入 ...qp: QpInterface;...QpInterface; 但没有用。在参数中输入 ...qp 的最佳方式是什么?

Until spread types are implemented in TypeScript, you can use intersection type为此:

interface searchClient {
  searchForValues({
    name,
    query,
    ...qp,
  }: {
    name: string;
    query: string;
  } 
    & QpInterface): Promise<any>;
 }