【发布时间】:2016-12-09 07:53:32
【问题描述】:
我不想在抽象类中描述一个抽象方法,它可以采用number 或string 并返回数字或字符串;
我使用| 符号告诉方法它的参数和返回类型可能因字符串而异。
然后我创建了两个类b 和c,它们是从抽象类a 扩展而来的,并尝试在没有参数和返回类型变化的情况下覆盖方法test()。
接下来,我要声明变量 x 哪个类型可能类似于 b 或 c 类,并且我正在根据随机语句创建其中一个类的实例。
最后我尝试调用test() 方法,但是TS 编译器给了我下面描述的错误。
abstract class a {
abstract test(x: string | number): string | number;
}
class b extends a {
test(x: number): number {
return x;
}
}
class c extends a {
test(x: string): string {
return x;
}
}
let x: b | c;
if (Math.random() > 0.5) {
x = new b()
} else {
x = new c()
};
x.test(1)
这是来自 TS 编译器的错误:
Cannot invoke an expression whose type lacks a call signature. Type '((x: number) => number) | ((x: string) => string)' has no compatible call signatures.
(property) test: ((x: number) => number) | ((x: string) => string)
也许我使用了错误的方法或者我误解了 TS 文档,如果是这样 - 请您指出我的目标的更好方法。
对不起,糟糕的类名和没有任何“小提琴” - 我找不到任何突出 TS 编译器错误的 js 游乐场网站,所以我推荐官方 TS Playground
【问题讨论】:
标签: javascript typescript