Typescript Interface with function. Subtype as parameter not accepted for implementing the interface

冷暖自知 提交于 2020-01-15 03:53:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!