问题
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
回答1:
Actually this makes sense because it is not safe to do this. Consider the following scenario:
class Example implements ExampleInterface{
someFunction = (foo:Foo)=>{
console.log("Hello World");
foo.someRandomFunction() // we can call this since foo is of type Foo
}
}
class Boo extends FooAbstract{
constructor(prop:any){
super(prop);
}
// no someRandomFunction method
}
var ex: ExampleInterface = new Example();
ex.someFunction(new Boo({})) // ok, Boo is derived from FooAbstract
If the compiler would allow the scenario in your question, the above code would compile but fail at runtime because someRandomFunction
does not exist on Boo
.
You can make the interface generic so you can specify what type of derived FooAbsrtact
you will use:
interface ExampleInterface< T extends FooAbstract >{
someFunction: (foo:T)=>any;
}
// now ok
class Example implements ExampleInterface<Foo>{
someFunction = (foo:Foo)=>{
console.log("Hello World");
foo.someRandomFunction()
}
}
class Boo extends FooAbstract{
constructor(prop:any){
super(prop);
}
// no someRandomFunction method
}
var ex: ExampleInterface<Foo> = new Example();
ex.someFunction(new Boo({})) // compile error as it should be
来源:https://stackoverflow.com/questions/49535848/typescript-interface-with-function-subtype-as-parameter-not-accepted-for-implem