Linter · Rules
prefer-destructuring
Require destructuring to read a property or an element into a variable
const name = user.name writes name twice. const { name } = user writes it once, and the next property you need goes into the same statement.
A property is only reported if the variable has the same name. An element is only reported if the index is a whole number written out, such as items[0].
--fix rewrites const name = user.name. Elements and plain assignments are reported but not fixed.
Configure
Off by default. To turn it on:
[lint.rules]
"prefer-destructuring" = "error" # or "warn"
Every option, set to its default. The ones that are commented out are unset by default.
[lint.rules]
"prefer-destructuring" = [
"error",
{
object = true,
array = true,
# VariableDeclarator = <object>,
# AssignmentExpression = <object>,
},
{
enforceForRenamedProperties = false,
},
]
Examples
Reported:
const name = user.name;
const first = items[0];
email = user.email;
Not reported:
const { name } = user;
const [first] = items;
({ email } = user);
const label = user.name;
const current = items[index];
const city = user?.city;
Options
The rule takes two objects. The first says what to check, and the second holds enforceForRenamedProperties.
[lint.rules]
prefer-destructuring = [
"error",
{ object = true, array = false },
{ enforceForRenamedProperties = true },
]
| Option | Default | What it does |
|---|---|---|
object | true | Report properties: const name = user.name. |
array | true | Report elements: const first = items[0]. |
enforceForRenamedProperties | false | Also report a property that goes into a variable with a different name, and a computed key. |
If you pass the first object, a key you leave out is false.
const first = items[0];
const label = user.name;
const value = settings[key];
To treat declarations and assignments differently, give the first object the keys VariableDeclarator and AssignmentExpression, each with its own object and array:
email = user.email;
first = items[0];
const email = user.email;