Reputation: 46509
I came across following issue, I have 2 classes i.e.
class Animal {
public talk() {
console.log('...');
}
}
and
class Dog extends Animal {
public talk(noise: string) {
console.log(noise);
super.talk()
}
}
As you can see original Animal.talk
method has no arguments and due to constraints of my application it can't have any, however some classes that extend it can take in additional noise
argument. This throws a type error since this argument is not initially on Animal. Hence I wanted to ask how to handle this correctly.
This is a very simplified example, real use case has various types of noise
and I'd like to avoid defining all of these as possible values of Animal.talk
and ideally keep it without arguments;
Upvotes: 1
Views: 61
Reputation: 299455
It is required that Dog accept both talk("string")
and talk()
in this case. If you pass a Dog to a function that takes an Animal, that function must be able to call animal.talk()
(or else you've violated substitutability). That means that noise
has to be optional:
class Dog extends Animal {
public talk(noise?: string) {
console.log(noise);
super.talk()
}
}
And then you just need to then deal with cases where noise
is not passed. (But that's not avoidable. You will always have to deal with cases where noise
is not passed.)
Upvotes: 1