在论证中,打字稿对象休息打字

时间:2017-11-16 00:22:36

标签: javascript typescript typescript-typings

我对Typescript有点新鲜,我可以为90%的代码库做一些打字。但是当谈到休息/差价运营商时,我绝对不知所措。今天我在代码中遇到了这个问题(我没有写这个),但我确实发现它不起作用:

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中的每个键/值对都由QpInterface键入。

这是一个示例函数调用:

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

我在文档上找不到相关内容。我尝试过...qp: QpInterface;...QpInterface;这些无法正常工作。在参数中键入...qp的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

Until spread types are implemented in TypeScript,您可以使用intersection type

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