这是一个例子:
class A {
func(): void {}
}
class B extends A {
func(a: number, b: string): void {}
}
B 类报错说 func()
实现不正确。
最终,我正在努力使这项工作:
var b: B;
b.func(0, ''); // func is overloaded by B
b.func(); // func is inherited from A
目前这在 Typescript 中可行吗?
更新:修复了代码,不小心使用了函数属性而不是方法。
最佳答案
当使用箭头函数时,你实际上并没有得到类方法,而是函数的类型/值的成员。
不同之处在于,虽然方法被添加到原型(prototype)中,但箭头函数被添加到构造函数中的实例中:
class MyClass {
method() {}
funct = () => {}
}
编译为:
var MyClass = (function () {
function MyClass() {
this.func = function () { };
}
MyClass.prototype.method = function () { };
return MyClass;
}());
当然可以,如果这是你想要的。
这样做的主要问题是重载和调用父方法并不那么简单。
在你的情况下,重载:
class A {
func(): void {}
}
class B extends A {
func(): void; // parent signature
func(a: number, b: string): void; // new signature
func(): void {
if (arguments.length === 0) {
super.func();
} else {
// actual implementation
}
}
}
关于子类中的 Typescript 方法重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39460333/