Tslint: object spread should not be preferred when Object.assign's first argument is a class instance

Created on 25 May 2017  ·  3Comments  ·  Source: palantir/tslint

Bug Report

  • __TSLint version__: 5.3

TypeScript code being linted

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

with prefer-object-spread enabled

Actual behavior

lint failure, auto-fix to use object spread

Expected behavior

nothing. this rule should ignore cases where the first argument to Object.assign is a class instance.

  • if --project is supplied, we can check if the type of the first argument is class-like
  • if no project is supplied and we're only doing syntactic checks, the best we can do is check for new ... and ignore the expression

as reported in https://github.com/palantir/tslint/issues/2618#issuecomment-303879255

Fixed Bug

Most helpful comment

If the first argument is not an object literal, the rule only produces an error if the result is assigned to something.
Assigning the return value of Object.assign only makes sense if the first argument is a CallExpression, NewExpression or similar. Everything else, e.g. an Identifier or PropertyAccessExpression should still be an error.
And that doesn't require the type checker.

All 3 comments

Object.assign has side effects on its first argument. (That's why TypeScript transpiles { ...x, ...y } to Object.assign({}, x, y).) The rule should only activate if the first argument is a fresh object literal.

The rule should only activate if the first argument is a fresh object literal.

Well, technically, you're right. But I often see mistakes where programmers are not careful about the side effects on the first argument and they provide a non-literal value anyway when they _actually_ meant to do the same thing as object spread. So I would still want this rule to catch that. Maybe it could be opt-in...

If the first argument is not an object literal, the rule only produces an error if the result is assigned to something.
Assigning the return value of Object.assign only makes sense if the first argument is a CallExpression, NewExpression or similar. Everything else, e.g. an Identifier or PropertyAccessExpression should still be an error.
And that doesn't require the type checker.

Was this page helpful?
0 / 5 - 0 ratings