网站搜索

oop - 抽象类中的 TypeScript 函数签名不需要与接口匹配


在下面的示例中,接口 IFoo 声明了一个函数签名,该签名需要两个数字参数。抽象类 BaseFoo 实现了这个接口,但以不同的签名声明了该函数。最后,具体类 Foo 扩展 BaseFoo 并实现 BaseFoo 的函数声明版本。

interface IFoo {
    func(x: number ): number
}

abstract class BaseFoo implements IFoo {
    abstract func(x: number): number
}

class Foo extends BaseFoo {
    func() { return -1 } // Does not match interface func declaration
}

let foo: IFoo = new Foo()  // Should not be able to instantiate a Foo as an IFoo
let y = foo.func()  // Should not be able to call without an argument
console.log(y)

这个人为的例子说明了现实生活中发生过的事情:我在代码库中有一个现有的接口。我更新了它的一个函数的签名,期望编译器能帮我找到所有需要更新的类。但没有错误。

为什么我被允许用一个与接口不匹配的函数签名实例化一个抽象类?