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#
const name = user.nameUse object destructuring.;
const first = items[0]Use array destructuring.;
email = user.emailUse object destructuring.;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.
{ "object": true }No problemsconst first = items[0];{ "object": true }, { "enforceForRenamedProperties": true }2 problemsconst label = user.nameUse object destructuring.;
const value = settings[key]Use object destructuring.;To treat declarations and assignments differently, give the first object the keys VariableDeclarator and AssignmentExpression, each with its own object and array:
{ "VariableDeclarator": { "object": true, "array": true }, "AssignmentExpression": { "object": false, "array": false } }No problemsemail = user.email;
first = items[0];{ "VariableDeclarator": { "object": true, "array": true }, "AssignmentExpression": { "object": false, "array": false } }1 problemconst email = user.emailUse object destructuring.;