【问题标题】:TypeScript - how to prevent overwriting class methods with variables in constructorTypeScript - 如何防止在构造函数中使用变量覆盖类方法
【发布时间】:2019-11-06 13:08:36
【问题描述】:

我有一个大型代码库,其中一些类成员设置了两次 - 一次作为方法,另一次在构造函数中显式设置。

下面是一个示例:

class SuperHero {
    public name: string;

    constructor(name: string) {
        this.name = name;

        // This line is a problem.
        this.hasCape = () => {
            return this.name === 'Batman';
        };
    }

    // I want this to be the canonical implementation.
    public hasCape() {
        return this.name === 'Batman' || this.name === 'Wonder Woman';
    }
}

看起来public readonly hasCape() 的语法无效。

有没有办法在编译器或 linter 级别强制方法声明为规范?

【问题讨论】:

  • 为了提高性能,强制重写构造函数中的所有类方法实际上是一种常见的做法。很多时候你会看到this.hasCape = this.hasCape.bind(this)
  • 您可以使用public readonly hasCape = () => { ... },但您仍然可以从构造函数中覆盖它,令人惊讶的是。它只防止从外部覆盖。
  • 您可以分配给构造函数中的任何readonly 成员。至少使用 Aaron 的语法可以防止方法在以后意外覆盖该方法。

标签: javascript typescript eslint tslint


【解决方案1】:

灵感来自Aaron Beall 的评论。这使得 hasCape 成为一个属性,一个函数,它是只读的。然后 typescript 编译器在从构造函数分配它时会引发错误。

    public get hasCape() {
        return () => this.name === 'Batman' || this.name === 'Wonder Woman';
    }

【讨论】:

  • 我非常喜欢这个,谢谢!接受代替适用于接受参数的函数的解决方案。
  • 这对一般情况没有帮助,因为您无法防止带参数的方法被覆盖。
  • 你有例子吗?我认为它也应该适用于接受参数/参数的函数/方法,例如:public get hasCape() { return (arg1) => this.name === 'Batman' || this.name === 'Wonder Woman' || arg1; }
猜你喜欢
  • 1970-01-01
  • 2016-02-27
  • 2019-04-17
  • 2014-05-22
  • 2011-10-26
  • 1970-01-01
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
相关资源
最近更新 更多