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
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: 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With