0

I have an Angular 15 app that uses a pipeline generated api-service. In the service I have a method for getting a list of items, but I am not sure how to pass parameters in any order.

public getList(page?: number | undefined, size?: number, type?: string, completed: boolean = false) {
  ....
}

When calling this method, I am able to send params as long as I use the correct number of params in the correct order, but I get an error when I try to pass in something specific

this.getList(undefined, 1) #returns list

this.getList(size: 1); #throws error

I remember being able to do this before, but I can't remember nor find the syntax for this

1 Answer 1

1

JavaScript and TypeScript do not support named parameters.

The closest you can get is defining an interface, and passing in an object that corresponds to that interface:

interface Params {
  page?: number;
  size?: number;
  type?: string;
  completed: boolean;
}

function getList(params: Params = { completed: false }) {
  // ...
}

getList({ size: 1, completed: false });

If you want to avoid having to repeat parameters for which you have a default value, you can define an object with default parameters, and use a Partial<Params>:

interface Params {
  page?: number;
  size?: number;
  type?: string;
  completed: boolean;
}

const defaultParams: Params = {
  completed: false
};

function getList(partialParams: Partial<Params>) {
  const params: Params = Object.assign({}, defaultParams, partialParams);
  // ...
}

getList({ size: 1 });
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.