I have a class which extends another class as shown below
abstract class FooAbstract{
constructor(someProp:any){
this.someProp = someProp;
}
someProp:any;
}
class Foo extends FooAbstract{
constructor(prop:any){
super(prop);
}
someRandomFunction(){
console.log("Something")
}
}
I have an interface which has a function as shown below
interface ExampleInterface{
someFunction: (foo:FooAbstract)=>any;
}
Now I want to implement the interface but want to pass subtype as parameter of the function someFunction in the interface implementation as shown below
class Example implements ExampleInterface{
someFunction = (foo:Foo)=>{
console.log("Hello World");
}
}
Typescript is warning that the implementation of someFunction is incorrect and the type Foo and FooAbstract are incompatible. I want to understand why can't I implement the function someFunction by requiring as a parameter a subtype of FooAbstract
FooAbstracts areFoos - ifsomeFunctionrelied onsomeRandomFunctionthen it couldn't accept some implementers ofFooAbstract. You can't narrow parameter types (similarly you can't broaden return types).