typescript/parameter-properties 风格
它的作用
要求或禁止在类构造函数中使用参数属性。
为什么这是个问题?
混合使用参数属性和类属性声明会使类的风格不一致,更难以维护。
示例
{ "prefer": "class-property" }(默认)
此规则下 错误 的代码示例:
ts
class Foo {
constructor(private name: string) {}
}此规则下 正确 的代码示例:
ts
class Foo {
name: string;
constructor(name: string) {
this.name = name;
}
}{ "prefer": "parameter-property" }
此规则下 错误 的代码示例:
ts
class Foo {
name: string;
constructor(name: string) {
this.name = name;
}
}此规则下 正确 的代码示例:
ts
class Foo {
constructor(private name: string) {}
}配置
此规则接受一个包含以下属性的配置对象:
allow
type: array
默认值: []
根据 prefer 选项,允许与参数属性或类属性一起使用的修饰符。
allow[n]
type: "private" | "private readonly" | "protected" | "protected readonly" | "public" | "public readonly" | "readonly"
prefer
type: "class-property" | "parameter-property"
默认值: "class-property"
是否优先使用参数属性或类属性。
如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"rules": {
"typescript/parameter-properties": "error"
}
}bash
oxlint --deny typescript/parameter-properties