且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

具有功能的Typescript接口。子类型不能作为参数用于实现接口

更新时间:2022-11-22 20:11:41

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

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