子类中的 Typescript 方法重载

标签 typescript

这是一个例子:

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/

相关文章:

angular - 在 ionic 2 中将 nav.push 与侧边菜单一起使用

即使在排除它们之后, typescript 也会在 node_modules 下编译类型

typescript - 如何使用 Typescript Compiler API 生成全局属性访问表达式?

javascript - 在JS中对json数组使用find方法时仅发送键值

javascript - chart.js 中圆环图上的自定义数据位置

typescript - 如何强制方法参数值成为接口(interface)的元素

检测到 Angular 编译器,但它是错误类的实例

javascript - TypeScript 和 Socket.io

angularjs - 有没有人尝试过在 AngularJS HTML 页面中使用 typescript 枚举?

javascript - 在 Typescript 和 Eslint 中使用别名时找不到模块