typescript/prefer-readonly-parameter-types Nursery
What it does
Require function and method parameters to use readonly-compatible types.
Why is this bad?
Mutable parameter types make accidental mutation easier and weaken function contracts. Readonly parameter types communicate intent and improve API safety.
Examples
Examples of incorrect code for this rule:
function update(items: string[]) {
items.push("x");
}
function consume(obj: { value: string }) {
obj.value = obj.value.trim();
}Examples of correct code for this rule:
function update(items: readonly string[]) {
return items.length;
}
function consume(obj: Readonly<{ value: string }>) {
return obj.value;
}Configuration
This rule accepts a configuration object with the following properties:
allow
type: array
default: []
Type/value specifiers that should be exempt from this rule.
allow[n]
type: string
Type or value specifier for matching specific declarations
Supports four types of specifiers:
- String specifier (deprecated): Universal match by name
"Promise"- File specifier: Match types/values declared in local files
{ "from": "file", "name": "MyType" }
{ "from": "file", "name": ["Type1", "Type2"] }
{ "from": "file", "name": "MyType", "path": "./types.ts" }- Lib specifier: Match TypeScript built-in lib types
{ "from": "lib", "name": "Promise" }
{ "from": "lib", "name": ["Promise", "PromiseLike"] }- Package specifier: Match types/values from npm packages
{ "from": "package", "name": "Observable", "package": "rxjs" }
{ "from": "package", "name": ["Observable", "Subject"], "package": "rxjs" }checkParameterProperties
type: boolean
default: true
Whether to check constructor parameter properties.
ignoreInferredTypes
type: boolean
default: false
Whether to ignore parameters without explicit type annotations.
treatMethodsAsReadonly
type: boolean
default: false
Whether mutable methods should be treated as readonly members.
How to use
To enable this rule using the config file or in the CLI, you can use:
{
"rules": {
"typescript/prefer-readonly-parameter-types": "error"
}
}oxlint --type-aware --deny typescript/prefer-readonly-parameter-types