Rush Stack商店博客活动
跳至主要内容

ae-missing-getter

“该属性___具有 setter 但没有 getter。”

备注

TypeScript 属性通常用于指示类似于读写变量的 API 行为。例如,样式指南通常建议

  • 属性 getter 不应执行昂贵/复杂的操作
  • 属性 getter 不应导致可观察的副作用(例如,读取属性会将流指针向前移动)
  • 属性 getter 应避免抛出异常

同样,声明没有 setter 的属性 getter 也是很奇怪的。在将值分配给变量后,开发者直观地会期望能够读取分配的值。

考虑以下示例

/**
* Represents a book from the catalog.
* @public
*/
export class Book {
private _title: string = 'untitled';

/**
* Sets the title of the book.
*/
// Error: (ae-missing-getter) The property "title" has a setter but no getter.
public set title(value: string) {
this._title = value;
}
}

const book: Book = new Book();
book.title = 'The Hobbit';
console.log('The title: ' + book.title); // prints "The title: undefined"

以上行为是违反直觉的。缺少 setter 很可能是 API 设计中的错误。API 提取器会报告 ae-missing-getter 错误。

如何修复

最简单的解决方案是实现缺少的属性 getter。请注意,getter 的文档描述了这两种操作;属性 setter 无法具有文档注释

/**
* Represents a book from the catalog.
* @public
*/
export class Book {
private _title: string = 'untitled';

/**
* Gets or sets the title of the book.
*/
public get title(): string {
return this._title;
}

public set title(value: string) {
this._title = value;
}
}

const book: Book = new Book();
book.title = 'The Hobbit';
console.log('Title: ' + book.title); // prints "Title: The Hobbit"

或者,如果您的 API 确实需要成为单向操作,您应该将其设计为方法而不是属性

/**
* Represents a book from the catalog.
* @public
*/
export class Book {
private _title: string = 'untitled';

/**
* Sets the title of the book.
*/
public setTitle(title: string): void {
this._title = title;
}
}

涉及“继承” getter 的一个陷阱

如果您选择禁用 ae-missing-getter 验证,请注意继承的属性:如果子类通过仅指定 setter 来覆盖属性,则 getter 将变得未定义。与其他一些语言不同,ECMAScript getset 属性构成单个 访问器属性,该属性被覆盖。请参阅 此游乐场链接 以获取示例。

另请参阅