【发布时间】:2018-12-12 08:20:58
【问题描述】:
我目前正在使用 TypeScript(2.9.2 版)开发一个项目,并且遇到了意外的多态行为。在 Java 和 C# 中,接口与类一样定义多态行为——也就是说,在下文中,item1 可以是 A 类型,因为它可以是类型B,而item2 可以是C 类型,因为它可以是D 类型:
interface A { }
class B implements A { }
class C { }
class D extends C { }
但在 TypeScript 中,情况似乎并非如此。我大约有以下设置:
interface A {
new (str: string): Module;
someFunction(str: string): A;
}
class B implements A {
constructor(str: string) { /* ... */ }
someFunction(str: string): B { /* ... */ }
}
编译器似乎对B的someFunction()的返回类型有问题,但是根据我对多态性的理解,因为B实现A,如果函数返回类型为A的东西,那么它也应该能够返回B 类型的东西。话虽如此,“类型为A”的东西是没有意义的,因为接口不能被实例化,并且只是类之间的无形协议或契约。如果 A 改为抽象类,那么多态行为应该像我预期的那样运行似乎是合理的——它确实如此——但在我正在构建的库的范围内,它似乎更适合 @987654339 @ 成为一个接口。
编译器特别给出的问题如下在声明B的someFunction()的那一行:
[ts]
Property 'someFunction' in type 'B' is not assignable to the same property in base type 'A'.
Type '(str: string) => B' is not assignable to type '(str: string) => A'.
Type 'B' is not assignable to type 'A'.
Types of property 'someFunction' are incompatible.
Type '(str: string) => B' is not assignable to type '(str: string) => A'.
(method) Project.B.someFunction(str: string): B
部分问题似乎在于我在A 中声明了一个构造函数。如果我删除该构造函数定义,问题就解决了,但我需要该定义成为协议的一部分,即它的基本含义是类型为A。
考虑到我期望的多态行为,我应该如何编写我的接口,或者我应该使用抽象类来代替?我如何带来这种多态行为?
【问题讨论】:
标签: javascript typescript oop interface polymorphism