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

bjwhip
  • 407
  • 1
  • 9
  • 18

1 Answers1

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 });
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156