How to declare a function that accepts only two or zero arguments?

Viewed 654

In TypeScript, if I declare a function like this

function foo(arg1?: any, arg2?: any)

Then the compiler won't complain if I call the function with

  • Zero arguments
  • One argument
  • Two arguments

How should I declare the function if I want the compiler to complian about one argument but not two or zero?

4 Answers

You can use function overload: https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads

// Start with most specific overload signature
function foo(arg1: any, arg2: any): any; 

// And then, less specific overload signature
function foo(): any; 

// At the end, write your function implementation
function foo(arg1?: any, arg2?: any) {
  console.log(arguments);
}

foo(1, 'test'); // Ok
foo(); // Ok 
foo('a'); // Compile error

What I like to do in these type of situations:

interface FooArgs {
    arg1: any;
    arg2: any;
}

function foo(arg?: FooArgs)
{
    // do stuff
}

Called like this: foo({arg1: 'arg', arg2: 'arg2}) or foo().


The typescript compiler will show an error if you try it like this:

foo({arg1: 'arg'})
Argument of type '{ arg1: number; }' is not assignable to parameter of type 'FooArgs'. Property 'arg2' is missing in type '{ arg1: number; }' but required in type 'FooArgs'.

Try it here

Just for completeness, it's also possible to use spread args and only have one definition:

function foo(...args: [] | [ any, any ]) {
  console.log(args);
}

foo(1, 'test'); // Ok
foo(); // Ok 
foo('a'); // Compile error

Playground Link

in this case I would transform params into array as:

function foo(params?: [any, any])  {

}

foo() //works
foo([0]) //error
foo([0, 0]) //works

or into object and do it like this:

interface BarArgs {
    arg1: any;
    arg2: any;
}

function bar(arg?: BarArgs) {

}

bar() //works
bar({arg1: 0}) //error
bar({arg2: 1}) //error
bar({arg1: 0, arg2: 1}) //works
Related