Mmohebifar

javascript-eslint-prefer-destructuring-assignment

Replace eligible property/index access assignments with equivalent object or array destructuring in JavaScript/TypeScript codebases to improve readability, consistency, and lint compliance with ESLint’s `prefer-destructuring` rule.

javascripttypescripteslintdestructuringrefactor
Public
0 executions

Run locally

npx codemod javascript-eslint-prefer-destructuring-assignment

javascript-eslint-prefer-destructuring-assignment

Replace eligible property access assignments with equivalent destructuring in JavaScript/TypeScript codebases to improve readability, consistency, and lint compliance with ESLint’s prefer-destructuring rule. A narrow opt-in mode also supports some array-index rewrites.

Installation

bash

Usage

This codemod rewrites safe property reads like const x = obj.x, const label = obj['label'], and x = obj.x into equivalent destructuring assignments. Array-index rewrites are available only when array=true, and even then only for syntactically guaranteed iterable bases such as array literals; common cases like const first = arr[0] and first = arr[0] intentionally remain unchanged because iterability is not provable from syntax alone.

Default-safe behavior:

  • Preserves renames such as const renamed = obj.value by emitting { value: renamed }.
  • Skips dynamic keys or indices, optional chaining, private fields, side-effecting bases like getObj().x, typed TS bindings that cannot be migrated safely, multi-declarator collapses such as const a = src.a, b = src.b, and mixed declarations that include unrelated declarators.

Workflow parameters:

  • object=true|false: enable or disable object-property rewrites.
  • array=true|false: enable or disable narrow numeric-index array rewrites for syntactically guaranteed iterable bases only. Defaults to false because iterability is not generally provable from syntax alone, so ordinary variable reads like arr[0] are still skipped.
  • enforceRenaming=true|false: when false, only rewrite object properties whose local binding name already matches the property name.

Local examples:

bash

Development

bash

License

MIT

Before

This is one example from the codemod's test cases. The codemod may handle many more cases.

Ready to contribute?

Build your own codemod and share it with the community.