I want type a function in such a way that it can be called with either no arguments or all arguments (two in my case).
I tried this:
function foo(a: string, b: number): string
function foo(a?: string, b?: number): string
function foo(a?: string, b?: number): string {
return a + (b ? b.toString() : '')
}
…but I can still provide just one argument and receive no errors:
foo(); // ok
foo('hello', 42); // ok
foo('oops'); // should error, but doesn't
Here's a TypeScript playground link.
Is this possible?
function foo(a: string, b: number): string
function foo(): string // YOU NEED NO ARGS YOU WRITE NO ARGS
function foo(a?: string, b?: number): string {
return a + (b ? b.toString() : '')
}