Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix Eslint error "prefer-destructuring"?

I wanted to shorten an object literal in ES6 like this:

const loc = this.props.local;

The reason is loc.foo(); is a lot easier to type than this.props.local.foo();

But now ESLint complains:

Use object destructuring: prefer-destructuring

I've read the error description on eslint.org but I don't understand it. They have an example which looks very similar to my code but theirs seem to be ok?

var foo = object.bar;

How can I fix the error without setting it to ignore in the .eslintrc file?

like image 342
Timo Ernst Avatar asked Nov 20 '17 15:11

Timo Ernst


People also ask

What is Destructuring in TypeScript?

Tuples in TypeScript are basically a simple Array with definite length and definite Data-type. Destructuring means breaking the structure. In this article we will see how Destructuring of tuple in TypeScript work. Destructuring is simply breaking up into part and assigning to variables.

What is ES6 Destructuring?

The destructuring assignment is a cool feature that came along with ES6. Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. That is, we can extract data from arrays and objects and assign them to variables.

Why is JavaScript Destructuring important?

Destructuring in Functions In destructuring, we can set default values too: If we pass the value in a division, it'll set to that division. The power of destructuring is not that apparent in a raise. It's still advantageous to destructure and build the arrays, as you can see here.


3 Answers

change your code from:

const local = this.props.local;

to:

const { local } = this.props;

They are equivalent and you can call local.foo() in the same way. except that the second use object destructuring.

like image 93
Badis Merabet Avatar answered Oct 24 '22 06:10

Badis Merabet


It's a new construct in ES 6 that allows you to match property of an object in assignment. The syntax you need is:

const { local: loc } = this.props

which translates to: "declare a constant loc and assign it the value of property local from this.props".

like image 6
ilmirons Avatar answered Oct 24 '22 06:10

ilmirons


It's telling you to use

const {props: {local: loc}} = this;
like image 3
Bergi Avatar answered Oct 24 '22 06:10

Bergi