When working with a function that has both optional and required parameters, such as:
example(page: number, perPage: number, name?: string, status?: boolean) {
// Body
}
There may be scenarios where only one of the optional parameters is provided, like so:
example(1, 25, true);
In this case, the true
value will be treated as the name
parameter, which is not the desired outcome. Rearranging the parameter order in the function declaration does not solve this issue, as there are situations where only certain parameters are available.
One approach that has been explored is passing a null
value for the parameter that is not present:
example(1, 25, null, true);
In the example.service.ts file, the script checks if the passed parameter is not null:
example(page: number, perPage: number, name?: string, status?: boolean) {
if (name !== null) {
// body
}
if (status !== null) {
// body
}
}
However, this method may not be the most effective way to handle these scenarios.