1

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!

1
  • You can also use null to omit the value. But yes, in case of ambiguity (like calling this function with two string values, for example) second param will be considered a val_b value. That's another reason to use named params btw. Commented Jun 25, 2022 at 9:41

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

True. That's a much more beautiful solution! Thank you!
1

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");

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.