简体   繁体   English

Typescript对象在参数中进行其余输入

[英]Typescript object rest typings in argument

I'm a bit new to Typescript, and I can do typings for 90% of my codebase. 我对Typescript有点陌生,我可以为90%的代码库进行打字。 But when it comes to rest/spread operators, I am absolutely at a loss. 但是当涉及到休息/分散操作员时,我绝对感到茫然。 I happened upon this today in our code (I did not write this) but I did figure out that it doesn't work: 我今天在我们的代码中遇到了这个(我没有写这个),但是我确实发现它不起作用:

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;
}

It doesn't work because qp is designating the name of the key in the typing whereas what I want to type is the ...qp part. 它不起作用,因为qp在键入中指定键的名称,而我要键入的是...qp部分。 Every key/value pair in ...qp is typed by the QpInterface. ...qp每个键/值对均由QpInterface键入。

Here's a sample function call: 这是一个示例函数调用:

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

I couldn't find much on this on the documentation. 我在文档中找不到太多。 I've tried putting ...qp: QpInterface; 我试过把...qp: QpInterface; and ...QpInterface; ...QpInterface; which didn't work. 这没有用。 What is the best way to type ...qp in the argument? 在参数中键入...qp的最佳方法是什么?

Until spread types are implemented in TypeScript , you can use intersection type for this: 在TypeScript中实现扩展类型之前 ,您可以为此使用交集类型

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM