Skip to content
← Back to rules

typescript/prefer-readonly-parameter-types Nursery

💭 This rule requires type information.

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:

ts
function update(items: string[]) {
  items.push("x");
}

function consume(obj: { value: string }) {
  obj.value = obj.value.trim();
}

Examples of correct code for this rule:

ts
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:

  1. String specifier (deprecated): Universal match by name
json
"Promise"
  1. File specifier: Match types/values declared in local files
json
{ "from": "file", "name": "MyType" }
{ "from": "file", "name": ["Type1", "Type2"] }
{ "from": "file", "name": "MyType", "path": "./types.ts" }
  1. Lib specifier: Match TypeScript built-in lib types
json
{ "from": "lib", "name": "Promise" }
{ "from": "lib", "name": ["Promise", "PromiseLike"] }
  1. Package specifier: Match types/values from npm packages
json
{ "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:

json
{
  "rules": {
    "typescript/prefer-readonly-parameter-types": "error"
  }
}
bash
oxlint --type-aware --deny typescript/prefer-readonly-parameter-types

References