component-property-use-readonly
属性应为只读时发出警告
- ⭐️ 此规则包含在 Flat Config 的
rdlabo.configs.recommended预设中。- ✒️ 在命令行中使用
--fix选项可以自动解决该规则所报告的一些问题。
此规则要求,由 Angular 组件声明的非功能属性必须使用readonly修饰符。该规则适用于已初始化的、未初始化的、静态的、计算得出的、经过装饰的、具有软私有属性的以及具有硬私有属性的属性。同时,该规则能够自动为这些属性添加readonly修饰符。
规则详情
只有用@Component()装饰的属性才会被考虑进来。方法、getter、setter、箭头函数定义的属性、函数表达式定义的属性、已经标记为readonly的属性,以及其他类的属性则会被忽略。
选项
{
"rules": {
"@rdlabo/rules/component-property-use-readonly": [
"error",
{
"ignorePrivateProperties": true
}
]
}
}
ignorePrivateProperties
- 类型:
boolean - 默认值:
false
当值为true时,使用 TypeScript 的private修饰符声明的属性,以及 ECMAScript 中的#关键字声明的私有属性将被忽略。而公共属性、受保护的属性以及静态属性仍然会被检查。
示例
错误示例
@Component({
selector: 'app-example',
template: '<div>example</div>',
})
export class ExampleComponent {
x = 1;
public y = 2;
private z = 3;
protected w = 4;
#secret = 42;
static a = 1;
['foo'] = 1;
@Input() i = 8;
h: number;
}
正确示例
@Component({
selector: 'app-example',
template: '<div>example</div>',
})
export class ExampleComponent {
readonly x = 1;
public readonly y = 2;
private readonly z = 3;
protected readonly w = 4;
readonly #secret = 42;
static readonly a = 1;
readonly ['foo'] = 1;
@Input() readonly i = 8;
readonly h: number;
}
设置 ignorePrivateProperties: true 时,私有属性可以保持可写:
@Component({
selector: 'app-example',
template: '<div>example</div>',
})
export class ExampleComponent {
private privateProp = 1; // 无错误
#secretProp = 2; // 无错误
public readonly publicProp = 3;
}
何时启用
若组件属性应公开稳定的引用,而可写状态由 Signals 或 ViewModel 管理,请启用此规则。