具有功能的Typescript接口。子类型不能作为参数用于实现接口 [英] Typescript Interface with function. Subtype as parameter not accepted for implementing the interface

查看:177
本文介绍了具有功能的Typescript接口。子类型不能作为参数用于实现接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可扩展另一个类的类,如下所示

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;
}

现在,我想实现该接口,但希望将子类型作为界面实现中的函数 someFunction ,如下所示

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警告 someFunction的实现不正确,并且Foo和FooAbstract类型不兼容。我想了解为什么我不能通过要求 FooAbstract

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

推荐答案

实际上这是有道理的,因为这样做并不安全。请考虑以下情形:

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

如果编译器允许您提出问题,则上面的代码将编译但在运行时失败,因为 Boo <中不存在 someRandomFunction / code>。

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.

您可以使接口通用,因此可以指定哪种类型的派生 FooAbsrtact 您将使用:

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

这篇关于具有功能的Typescript接口。子类型不能作为参数用于实现接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆