typescript/prefer-readonly-parameter-types Pedantic
作用
要求函数和方法参数使用与 readonly 兼容的类型。
为什么这不好?
可变参数类型更容易导致意外修改,并削弱函数契约。 readonly 参数类型能够传达意图,并提升 API 安全性。
示例
以下是此规则的错误代码示例:
ts
function update(items: string[]) {
items.push("x");
}
function consume(obj: { value: string }) {
obj.value = obj.value.trim();
}以下是此规则的正确代码示例:
ts
function update(items: readonly string[]) {
return items.length;
}
function consume(obj: Readonly<{ value: string }>) {
return obj.value;
}配置
此规则接受一个具有以下属性的配置对象:
allow
type: array
default: []
应豁免于此规则的类型/值说明符。
allow[n]
type: object | string
用于匹配特定声明的类型或值说明符
支持四种说明符类型:
- 字符串说明符(已弃用):按名称进行通用匹配
json
"Promise"- 文件说明符:匹配在本地文件中声明的类型/值
json
{ "from": "file", "name": "MyType" }
{ "from": "file", "name": ["Type1", "Type2"] }
{ "from": "file", "name": "MyType", "path": "./types.ts" }- lib 说明符:匹配 TypeScript 内置 lib 类型
json
{ "from": "lib", "name": "Promise" }
{ "from": "lib", "name": ["Promise", "PromiseLike"] }- 包说明符:匹配来自 npm 包的类型/值
json
{ "from": "package", "name": "Observable", "package": "rxjs" }
{ "from": "package", "name": ["Observable", "Subject"], "package": "rxjs" }allow[n].from
type: "file"
必须为 "file"
allow[n].name
type: array | string
要匹配的类型或值的名称
名称说明符,可以是单个字符串或字符串数组
allow[n].name[n]
type: string
allow[n].path
type: string
可选的文件路径,用于指定类型或值必须声明于何处。 如果省略,则会匹配所有文件。
checkParameterProperties
type: boolean
default: true
是否检查构造函数参数属性。
ignoreInferredTypes
type: boolean
default: false
是否忽略没有显式类型注解的参数。
treatMethodsAsReadonly
type: boolean
default: false
是否将可变方法视为 readonly 成员。
如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"options": {
"typeAware": true
},
"rules": {
"typescript/prefer-readonly-parameter-types": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
options: { typeAware: true },
rules: {
"typescript/prefer-readonly-parameter-types": "error",
},
});bash
oxlint --type-aware --deny typescript/prefer-readonly-parameter-typesVersion
此规则在 v1.49.0 中添加。
