简体   繁体   中英

Typescript: Function with Multiple Parameters AND optional Parameter?

I'm currently trying to figure out how to pass multiple parameter inside a function with the "..." operator while also passing an optional parameter with the "?" operator.

The functions' header shall look like this:

public ThisIsAFunction(val_a: string, val_b?: string, ...val_c: string[]) {};

But since for the "..." - operator it is needed to set the parameter as the last one, but the "?" operator also needs to be set as the last item for being able to leave it without an input, it seems like the only option to use it like that would be:

public ThisIsAFunction("Test", undefined, "Test_one", "Test_two", "Test_three");

But is there also a way to use it without the need of writing "undefined" inside the parameter if I don't want to use val_b?

Thanks in Advance!

There is no way for TS to infer if you wanted to send the optional parameter or use the ...rest approach.

So you are right, that the only approach, without changing the function signature is to type the value yourself. You aren't limited to undefined , you can pass null for instance or any other value that would be neutral for your business logic.

The deeper question is why do you need this ? . There are other approaches that make this more readable.

Another approach would be to declare an interface/or type for the function args and pass them as an object and then use destructuring to get the values out of it.

Something similar to this:

interface ThisIsAFunctionArgs {
 val_a: string;
 val_b?: string;
 rest: string | string[] | undefined
}
public ThisIsAFunction( args: ThisIsAFunctionArgs)

Try something like this

Typescript Playground Link

function thisIsAFunction({ val_a, val_b }: { val_a: string, val_b?: string }, ...val_c: string[]) {
  console.log(val_a, val_b, val_c);
};

thisIsAFunction({ val_a: "foo" }, "bar", "baz");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM