猿问

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

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


下面是一个示例:


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


慕码人2483693
浏览 196回答 1
1回答
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答