Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use array destructuring (prefer-destructuring) error on eslint

Tags:

eslint

here is the part of my code that eslint doesn't like.

this.attributes.mb.start_date = this.dateInstance.config.defaultDate.split('T')[0]

How can I rewrite it to overcome this error?

like image 377
Petran Avatar asked Feb 22 '19 13:02

Petran


People also ask

Is it possible to use array destructuring in ESLint?

That seems reasonable, but then the base ESLint prefer-destructuring rule gives me a warning, even though TypeScript claims I'm not allowed to use array destructuring here. I think having a type-aware version of this rule would be beneficial.

What is destructuring in JavaScript ES6?

With JavaScript ES6, a new syntax was added for creating variables from an array index or object property, called destructuring. This rule enforces usage of destructuring instead of accessing a property through a member expression. Rule Details Options This rule takes two sets of configuration objects.

Is it possible to prevent array destructuring of non-iterable types?

Thanks. Happy to accept a PR if you'd like to add a type-aware version of the rule to prevent array destructuring of non-iterable types. In that case, could also implement a fixer, as we know for sure the type is fixable.

What is wrong with the ESLint prefer-destructuring rule in TS?

Another issue with the eslint prefer-destructuring rule in TS is if you apply a type declaration to the resulting variable: const obj = {xs: ['a', 'b', 'c']}; // type is {xs: string []} const xs: readonly string[] = obj.xs; xs.push('d'); // ~~~~ Property 'push' does not exist on type 'readonly string []'.


1 Answers

eslint prefer-destructuring rule has two properties, array and object, can be used to turn on or off the destructuring requirement for each of those types independently. By default, both are true.

With array property enabled, this is incorrect

const foo = ['one', 'two'];

const x = foo[0];   // incorrect

The correct way to destructure an array is:

const [one, two] = foo;

console.log(one); // "one"
console.log(two); // "two"

as the rule says to access the element by destructuring the array, so let's say if you have a large array and you want to access large array indices directly, then the array property of this rule is not recommended to be enabled, as destructuring does not match this use case very well. You can simply put this in your .eslintrc to disable enforcing array destructuring in such cases:

{
  "rules": {
    "prefer-destructuring": ["error", {"object": true, "array": false}]
  }
}
like image 169
Aaditya Thakkar Avatar answered Sep 22 '22 14:09

Aaditya Thakkar