5

I'm a bit new to Typescript, and I can do typings for 90% of my codebase. 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. Every key/value pair in ...qp is typed by the 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; and ...QpInterface; which didn't work. What is the best way to type ...qp in the argument?

1 Answer 1

7

Until spread types are implemented in TypeScript, you can use intersection type for this:

interface searchClient {
  searchForValues({
    name,
    query,
    ...qp,
  }: {
    name: string;
    query: string;
  } 
    & QpInterface): Promise<any>;
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.