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



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?


You can use function overload:

// 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) {

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

Answered By – Manuel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More