1

I have tried the answer of Pacerier from the question Skip arguments in a JavaScript function. But it does not seem to work.

I have a function with many arguments

this.service.list("all",null, null, localStorage.getItem('currentProgram'), null, 100, ...Array(2), environment.liveMode).subscribe(...)

The only way I've found is to write it one by one, like (,null, null or undefined,undefined).

I also set a test method to see if it was different, but it does not work as well.

test(a: any, b: any, c: any, d: string) {
    console.log(d)
}

ngOnInit() {
    this.test(...Array(3), "a")
}

I also tried other syntax proposed in the answer.

Is there a less verbose way to do this in TypeScript ?

1
  • Your function has a lot of optional arguments, this could be seen as a code smell. If you can refactor the function then you should take an object instead of multiple arguments like function foo(options: {a?: string, b?: number}). Commented Nov 11, 2021 at 1:16

2 Answers 2

2

In TypeScript if you want to skip a parameter you're obliged to explicitly pass undefined or null as the parameter value. Example:

function f(param1?: string, param2?: number, param3?: boolean) {
// do something
}

f(,,true); // ❌ Error
f(...[,,], true); // ❌ Error
f(...Array(2), true); // ❌ Error
f(undefined, undefined, true); // ✅ Works 
f(null, null, true); // ✅ Works

You can find more information and examples in this section of the TypeScript documentation: https://www.typescriptlang.org/docs/handbook/2/functions.html#optional-parameters

Sign up to request clarification or add additional context in comments.

1 Comment

@crg I could see that, I just described to you a few possible options.
0

The concept you are looking for is "named parameters".

TypeScript/JavaScript doesn't have explicit syntax support for this, but it's possible to achieve a similar result using object destructuring in the function parameter definition.

Here are some resources describing this approach:

Here is an example based on the test function in your question.

type TestParams = {
    a?: number[],
    b?: number,
    c?: boolean,
    d: string,
}

function test({a = [], b, c = false, d}: TestParams) {
    console.log(d)
}

test({d: 'my value'});
test({a: [1, 2, 3], d: 'my value'});

You get some nice features like being able to annotate the types for each property, or add default values for missing properties. Or, using TypeScript you can define which properties are optional or required.

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.