TypeScript - 如何防止在构造函数中使用变量覆盖 class 方法

TypeScript - how to prevent overwriting class methods with variables in constructor

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

下面是一个示例:

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 级别将方法声明强制为规范?

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

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