我有一个很大的代码库,其中一些类成员被设置了两次--一次作为方法,另一次显式地在构造函数中设置。
下面是一个例子,说明这可能是什么样子:
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级别将方法声明强制为规范?
发布于 2019-06-24 21:27:44
受到Aaron Beall评论的启发。这使得hasCape成为一个属性,这是一个函数,这是只读的。然后,类型记录编译器在从构造函数分配它时抛出一个错误。
public get hasCape() {
return () => this.name === 'Batman' || this.name === 'Wonder Woman';
}https://stackoverflow.com/questions/56741433
复制相似问题