Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有函数的Typescript接口。不接受子类型作为参数来实现接口_Typescript_Abstraction - Fatal编程技术网

带有函数的Typescript接口。不接受子类型作为参数来实现接口

带有函数的Typescript接口。不接受子类型作为参数来实现接口,typescript,abstraction,Typescript,Abstraction,我有一个类,它扩展了另一个类,如下所示 abstract类{ 构造函数(someProp:any){ this.someProp=someProp; } someProp:任何; } 类Foo扩展了footabstract{ 构造器(道具:任何){ 超级(道具); } someRandomFunction(){ console.log(“某物”) } } 我有一个界面,其功能如下所示 接口示例接口{ someFunction:(foo:foostract)=>any; } 现在我想实现接口,

我有一个类,它扩展了另一个类,如下所示

abstract类{
构造函数(someProp:any){
this.someProp=someProp;
}
someProp:任何;
}
类Foo扩展了footabstract{
构造器(道具:任何){
超级(道具);
}
someRandomFunction(){
console.log(“某物”)
}
}
我有一个界面,其功能如下所示

接口示例接口{
someFunction:(foo:foostract)=>any;
}
现在我想实现接口,但想在接口实现中将subtype作为函数someFunction的参数传递,如下所示

类示例实现ExampleInterface{
someFunction=(foo:foo)=>{
log(“你好世界”);
}
}

Typescript警告说someFunction的实现不正确,并且类型Foo和FooAbstract不兼容。我想了解为什么我不能通过要求作为参数的子类型FooAbstract来实现函数someFunction,实际上这是有意义的,因为这样做不安全。考虑下面的场景:

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
如果编译器允许您问题中的场景,则上述代码将进行编译,但在运行时失败,因为
someRandomFunction
Boo
上不存在

您可以将接口设置为通用接口,以便指定将使用哪种类型的派生
FooAbsrtact

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
接口示例接口{
someFunction:(foo:T)=>any;
}
//现在好了
类示例实现ExampleInterface{
someFunction=(foo:foo)=>{
log(“你好世界”);
foo.someRandomFunction()
}
}
类Boo扩展了footabstract{
构造器(道具:任何){
超级(道具);
}
//无随机函数法
}
var-ex:ExampleInterface=new-Example();
ex.someFunction(new Boo({}))//按原样编译错误

因为并非所有的
FooAbstract
s都是
Foo
s-如果
someFunction
依赖
someRandomFunction
,那么它就不能接受
FooAbstract
的一些实现者。您不能缩小参数类型(类似地,您也不能扩大返回类型)。是的,这很有意义。只抽象类,而保留函数实现。谢谢你的回复