Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

Rule suggestion: prefer object spread to Object.assign #2618

Closed
danvk opened this issue Apr 20, 2017 · 5 comments · Fixed by #2624
Closed

Rule suggestion: prefer object spread to Object.assign #2618

danvk opened this issue Apr 20, 2017 · 5 comments · Fixed by #2624

Comments

@danvk
Copy link
Contributor

danvk commented Apr 20, 2017

Now that TS supports the object-spread operator, the idea would be to suggest replacing code like this:

Object.assign({}, foo, bar);

with

{...foo, ...bar}

See https://github.com/airbnb/javascript#objects--rest-spread

@ajafff
Copy link
Contributor

ajafff commented Apr 20, 2017

@danvk You can already do that with the ban rule and add an appropriate message. This doesn't have automatic fixing though.

On second thought using ban would also disallow cases where you really want to assign properties of one object to another without creating a new one.

Object.assign(obj1, obj2);

@danvk
Copy link
Contributor Author

danvk commented Apr 21, 2017 via email

@etsuo
Copy link

etsuo commented May 24, 2017

For what it's worth, an Object Spread does not appear to be the exact equivalent of Object.assign:

value = Object.assign(new Model(), value)

In this case, value instanceOf Model is true.

value = {...new Model(), ...value};

Here, value is an instance of Object.

This auto-fix just broke a bunch of my unit-tests... no biggie... just turned it off, but I figured I'd mention it in case someone thought the two were exactly equivalent.

@adidahiya
Copy link
Contributor

adidahiya commented May 24, 2017

that's a good point @etsuo... the rule should probably make an exception for when the first argument to Object.assign is a new SomeConstructor(...) expression because spread is not functionally equivalent

edit: filed #2824

@danvk
Copy link
Contributor Author

danvk commented May 25, 2017 via email

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants