Home > Enterprise >  spread operator when flattening array gives - error TS2769
spread operator when flattening array gives - error TS2769

Time:02-04

I am trying to flatten an array and am getting an error - - error TS2769: No overload matches this call.

I did this in stackblitz and it worked fine.

The spread operator is getting the error: ...this.selectedInstitutions

  selectedInstitutions = [
    [{ displayValue: 'ABC', id: 781 }],
    [{ displayValue: 'DEF', id: 782 }],
  ];

  ngOnInit() {
    this.selectedInstitutions = [].concat(...this.selectedInstitutions);
  }

The error message is:

enter image description here

CodePudding user response:

When using [].concat(someValue), the empty array [] doesn't have any type specified and is inferred to be of never[] type.

From docs

The never type is assignable to every type; however, no type is assignable to never (except never itself).

So when strictNullChecks typescript option is enabled, you will get an error when trying to assign any other type to never[] which is exactly what happens when you do something as:

[].concat(...this.selectedInstitutions)

You can overcome the error by type casting as:

this.selectedInstitutions = ([] as any[]).concat(...this.selectedInstitutions);

Typescript playground

PS: Use of any type is discouraged, so if you already have defined a type for selectedInstitutions, use the same while type casting.

CodePudding user response:

I am not sure what you are trying to flatten. Your data is already flat, it's only 1 level deep (no inner nesting). Combining an array with data to a new array and assigning it back to itself doesn't do much, end result is always the same, what are you trying to accomplish?

Anyway, adding a type declaration should resolve the issue.

([] as string[]).concat('foo')

  ngOnInit() {
    this.selectedInstitutions = ([] as any[]).concat(...this.selectedInstitutions);
  }

Here is a working example: https://stackblitz.com/edit/angular-ivy-scfukg?file=src/app/app.component.ts

  •  Tags:  
  • Related