This isn't a case of overloading, which in TypeScript means that a function or method may be called with multiple distinct call signatures, and whose (single) implementation must be compatible with all of them. Here your B
class has a exportToCSV()
method with a single call signature and implementation; no overloading here. This is just overriding (albeit an illegal override).
So you are overriding the exportToCSV()
method from A
with one from B
. The problem is that the signature for B
's method violates the contract from A
. The basic principle involved in determining compatibility is substitutability (or the Liskov Substituion Principle): if B extends A
is true, then you should be able to use a B
in place of an A
. If I ask for an A
, and you hand me a B
, I should be able to use it like an A
without having anything blow up. Meaning the following line should be fine:
const a: A = new B(); // okay if B really extends A
a.exportToCSV([], []); // also okay if B really extends A
Things are a little murky because you've given the metadata
parameter the intentionally unsafe any
type, but if it were a regular type, it would be dangerous to do this. Like:
class B extends A {
exportToCSV(data: any[], headers: any[], metadata: string) {
metadata.toUpperCase();
}
}
If metadata
is a required parameter then the call a.exportToCsv([], [])
would cause a runtime error. By changing metadata
to an optional parameter, it is fixed because your implementation of the method in B
knows that it can't rely on it being passed in:
class B extends A {
exportToCSV(data: any[], headers: any[], metadata?: string) {
metadata.toUpperCase(); // error, metadata might be undefined
(metadata || "").toUpperCase(); // okay
}
}
So, you should decide whether you really want B
to be substitutable for A
(in which case you need the methods to be compatible) or whether you want B
's exportToCSV()
method to require a third parameter (in which case you should think about refactoring so that B
does not extends A
... maybe both B
and A
can extend something else? Or maybe A
could be made generic so B extends A<T>
for some relevant T
?). Anyway, hope that gives you some direction. Good luck!
Playground link to code