One key aspect of inheritance is the ability to treat any subclass just like its superclass. This means that the public interface of parent class instances must be preserved in child class instances, ensuring type safety when using a child class as if it were a parent class instance.
However, altering the interface breaks this contract, which is not permissible.
For instance, any subclass of A
should be passable to this function:
function getGame(instance: A) {
return instance.game('name')
}
If an instance of class B
is passed to this function, it will fail because the game
method requires two arguments for class B
, but only one for class A
.
As a result, Typescript does not permit this behavior.
There are various ways to address this issue, but here are two suggestions.
Solution 1:
Make the second parameter optional.
class B extends A {
game(a: string, b?: number): string{
return a + ' ' + b?.toString();
}
}
By making the second parameter optional, you can safely call instances of class B
with only one argument. Thus, treating a B
instance as an A
instance allows calling the game
method with just one argument.
When certain that it is a B
instance, the second argument can still be provided.
Playground