【问题标题】:Overriding super method in TypeScript重写 TypeScript 中的超级方法
【发布时间】:2021-10-26 01:42:39
【问题描述】:

我正在尝试重载/覆盖 TypeScript 中的超类方法,其中从属方法采用一个参数,而上级方法采用零。

我的 TypeScript 代码类似于以下内容:

// index.ts

class Super {
  create(): void {}
}

class Sub extends Super {
  create(arg: any): void {}
}

let sub = new Sub();
sub.create(1);

此代码产生以下错误:

Property 'create' in type 'Sub' is not assignable to the same property in base type 'Super'.
  Type '(arg: any) => void' is not assignable to type '() => void'. ts(2416)

为什么这不起作用?是因为转译后的 JavaScript 输出根本无法区分这两个类的继承关系吗?我将如何完成这样的事情?

【问题讨论】:

    标签: javascript typescript oop abstract-class


    【解决方案1】:

    在 TypeScript 中,子类的类型必须可分配给其父类的类型。这允许多态性工作:

    let sub: Sub = new Sub();
    // polymorphism: we can treat a Sub as a Super
    let parent: Super = sub; 
    

    但是,您的代码无效,因为在上述情况下,我们可以在不带参数的情况下调用parent.create();然而,实际运行的代码是Sub.create,根据合同要求存在arg

    总而言之:子类型的所有成员都必须可分配给父类型的相应成员。 (arg: any) => void 不能分配给 () => void

    【讨论】:

      【解决方案2】:
      // index.ts
      
      class Super {
          create(): void {}
      }
      
      class Sub extends Super {
          create(arg?: any): void {}
      }
      
      let sub = new Sub();
      sub.create(1);
      
      

      【讨论】:

        猜你喜欢
        • 2011-06-03
        • 2018-07-08
        • 2016-05-17
        • 2019-08-20
        • 2016-06-02
        • 2014-02-27
        • 2010-12-11
        • 1970-01-01
        相关资源
        最近更新 更多