【发布时间】: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