kuklyy
kuklyy

Reputation: 336

Parameters in function, some of them are optional some required

I have a function where I have some parameters, some of them are optional some required, e.g.

example(page: number, perPage: number, name?: string, status?: boolean) {
    // Body
}

Sometimes I call it with only status

example(1, 25, true);

It means that true there will be as name what is not the way I want to do this. Changing order in function declaration doesn't help because sometimes I only got the name.

I was trying something like this, and in my service check if parameter is not equal to null.

example(1, 25, null, true);

example.service.ts

example(page: number, perPage: number, name?: string, status?: boolean) {
    if (name !== null) {
        // body
    }
    if (status !== null) {
       // body
    }
}

But I don't think it's the best way to handle this.

Upvotes: 1

Views: 1621

Answers (4)

RAKESH HOLKAR
RAKESH HOLKAR

Reputation: 2197

Simply Pass just param in the form of object and iterate that object in method

example(paramObj) {
    //iterate params here
    let paramArr = Object.keys(paramObj)

}

//calling
example({name:'Xyz Person'});

Upvotes: 0

nash11
nash11

Reputation: 8660

When you don't pass any value to an optional parameter, their value becomes undefined (Source: docs). So you can just pass undefined for that particular parameter.

To call example() with only status

example(1, 25, undefined, true);

Upvotes: 1

Mukesh Soni
Mukesh Soni

Reputation: 6668

There are a few ways you can handle this. The first one is by passing the third argument as undefined

example(1, 25, undefined, true);

Another way is to accept a single argument which is an object

interface Options {
  page: numberl; perPage: number; name?: string; status?: boolean;
}

This makes your function behave like it takes in named arguments.

example({page: 1, perPage: 25, status: true});

// in your function you can use destructuring for brevity

interface Options {
  page: number; perPage: number; name?: string; status?: boolean;
}

example(options: Options) {
   const {page, perPage, name, status} = options
    // Body
}

Upvotes: 1

Alexander Andryichenko
Alexander Andryichenko

Reputation: 177

Not sure, but have you tried passing object instead of list of arguments?

example(data: {page: number, perPage: number, name?: string, status?: boolean}) {
  //code goes here
}
example({page: 1, perPage: 25, status: true})

In this case you will get exact value you passed in the object

Upvotes: 5

Related Questions