The compiler is indicating that func(b, a)
requires a second argument whereas the func
method of Foo
does not. To resolve this error, you can make a
optional in the implementation:
const f: Foo = {
func(b, a?) {
// ^-- optional
}
}
It's worth noting that it may not always be feasible to find a solution that will compile. Function overloads statements allow for looser typing in their implementation compared to call signatures, but this doesn't apply to overloaded function expressions:
function barFunc(a: string): number;
function barFunc(b: number, a: string): string;
function barFunc(b: string | number, a?: string) {
return typeof b === "string" ? b.length : a // okay
}
type Bar = {
func(a: string): number;
func(b: number, a: string): string;
}
const g: Bar = {
func(b, a?) { // error!
return typeof b === "string" ? b.length : a
}
}
A feature request exists at microsoft/TypeScript#47669 for arrow functions to handle overloading like function statements do, however, this is not currently supported by the language.
If faced with an impossible-to-implement overloaded arrow function, consider refactoring to a function statement:
const h: Bar = { func: barFunc }; // okay
Alternatively, use type assertions to relax type checking enough to enable compilation:
const i: Bar = {
func(b, a?) {
return (typeof b === "string" ? b.length : a) as any // okay
}
}
Playground link to code