Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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?

like image 907
aabuhijleh Avatar asked Sep 18 '25 14:09

aabuhijleh


2 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
like image 126
Manuel Avatar answered Sep 22 '25 18:09

Manuel


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

like image 21
Josef Avatar answered Sep 22 '25 20:09

Josef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!