Joshua Ohana
Joshua Ohana

Reputation: 6121

Getting TypeScript compilation error on Object.assign, but everything works great

Apparently this is a known issue. The suggested workaround make my IDE stop complaining, and it runs and works fine, but I'm getting Angular CLI build TS errors which cause my CI/CD pipeline to fail.

The offending line is Object.assign(...args), where args is a dynamically sized array of objects, resulting in the below error

error TS2557: Expected at least 1 arguments, but got a minimum of 0.

Full code and context is

_.chain(myObjects)
.groupBy((obj: MyObject) => obj.someParam)
.each((args: [MyObject, MyObject, MyObject]) => {
  Object.assign(...args);
});

the 3rd line used to be args: MyObject[] but that caused IDE errors, so per various threads including https://github.com/Microsoft/TypeScript/issues/4130 I changed it to the above, but I'm still getting the errors on build

As mentioned, it runs and works perfectly, the Object.assign(...args) beautifully merges all objects in the args array. The only issue is that compiler barfs and fails my CI/CD pipeline.

Upvotes: 1

Views: 497

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149010

The issue is that Object.assign requires at least one argument, but the type MyObject[] could be an empty array. You have to convince the compiler in some way that there's at least entry in the array. For example:

_.chain(myObjects)
.groupBy((obj: MyObject) => obj.someParam)
.each(([target, ...rest]: MyObject[]) => {
  Object.assign(target, ...rest);
});

Or if you're comfortable 'cheating' a little with the as keyword:

_.chain(myObjects)
.groupBy((obj: MyObject) => obj.someParam)
.each((args: MyObject[]) => {
  Object.assign(...args as [MyObject]);
});

Upvotes: 2

Related Questions