The error TS2769 occurs when using the spread operator to flatten an array

I've been working on flattening an array, but unfortunately I keep encountering an error - TS2769: No overload matches this call.

Oddly enough, when I tested this in stackblitz, it worked perfectly.

The issue seems to be related to the spread operator: ...this.selectedInstitutions

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

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

This is the exact error message I'm receiving:

https://i.sstatic.net/6MTNw.png

Answer №1

When employing [].concat(someValue), the void array [] doesn't possess a specified type and is deduced to be of never[] nature.

Referencing information from the documentation

The never diversity can be assigned to any sort; nonetheless, no category can be appointed to never (aside from never itself).

Thus, when the strictNullChecks typescript option gets activated, an error will occur upon attempting to designate any distinct kind to never[], which occurs explicitly like so:

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

To bypass this mistake, you can undertake type casting in the following manner:

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

Try it out on the Typescript playground

PS: Refrain from using the any classification whenever feasible. If you've already defined a category for selectedInstitutions, apply that same specification while performing type casting.

Answer №2

It seems that the data you are attempting to manipulate is already in a flat structure, with no nested levels. Trying to combine an array with itself doesn't change the end result. What is your goal with this operation?

One solution could be adding a type declaration to address the issue.

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

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

For reference, check out this functional demo: https://stackblitz.com/edit/angular-ivy-scfukg?file=src%2Fapp%2Fapp.component.ts

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting the dispatch type in Redux using Typescript

I'm new to typescript and I'm trying to figure out what type should be assigned to the dispatch function. Currently, I am using 'any', but is there a way to map all actions to it? Here's how my code looks like: interface PropType ...

Trouble with scrolling on Kendo chart while using mobile device

I am facing an issue with multiple kendo charts on my website. These charts have panning and zooming enabled, but in the mobile view, they take up 100% of the width which causes touch events to not work properly for scrolling. I attempted to attach an even ...

How come TypeScript doesn't recognize my MongoDB ObjectID as a valid type?

Currently, I am working with Node.js, MongoDB, and TypeScript. The code snippet below is error-free: const ObjectID = require("mongodb").ObjectID; const id = new ObjectID("5b681f5b61020f2d8ad4768d"); However, upon modifying the second line as follows: ...

Angular 5 Error Messages for HTTP Interceptors

I'm facing an issue regarding Angular 5: HTTP Interceptors. I am still new to this, so please bear with me as I grasp the concepts. Here is the error message that I encountered: compiler.js:19514 Uncaught Error: Provider parse errors: Cannot instan ...

How can you incorporate TypeScript's dictionary type within a Mongoose schema?

When using TypeScript, the dictionary type format is: { [key: string]: string; } However, when I try to define a custom schema in mongoose, it doesn't work as expected. const users = new Schema({ [key: string]: String, }); I also attempted t ...

Unleashing the power of joint queries in Sequelize

Project.data.ts import { DataTypes, Model, CreationOptional, InferCreationAttributes, InferAttributes, BelongsToManyGetAssociationsMixin, BelongsToManySetAssociationsMixin, BelongsToManyAddAssociationsMixin } from 'sequelize'; import sequelize fr ...

Combine values from 2 distinct arrays nested within an array of objects and present them as a unified array

In my current array, the structure looks like this: const books[{ name: 'book1', id: '1', fromStatus: [{ name: 'Available', id: 1 }, { name: 'Free', id: 2 }], t ...

I encountered an issue with Svelte (Vite) + Bootstrap 5 + SvelteStrap where it gave me the error message stating: "Cannot assign type 'string' to type 'ButtonColor'"

I am currently working with Svelte (Vite) + Bootstrap 5 + SvelteStrap. The code I have written is as follows: <head> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_ ...

Retrieve the desired destination URL in the CanActivate guard when lazily loading modules in Angular

I am facing an issue with retrieving the target URL in the canActivate guard. Even though I have set up preloadingStrategy: PreloadAllModules in RouterModule.forRoot, the url property of ActivatedRoute does not contain the path. Here are the contents of bo ...

What kind of conditions does SonarQube report as being uncovered?

According to SonarQube, there are uncovered conditions on all the arguments passed to constructors for each component in my Angular project, as well as any elements decorated with @Input(). What specific conditions is SonarQube referring to, and how can I ...

When transforming a function into a custom command, the expected outcome may vary

There is a function that retrieves all CSS properties and values of an element: function fetchAllCssPropertiesAndValues(element: Element) { const style = window.getComputedStyle(element) const propertiesAndValues = {} for (let i = 0; i < st ...

What happens when a CSS module is exported as an empty object?

My go-to for creating projects is using TypeScript and create-react-app. I recently incorporated the typings-for-css-modules-loader and dabbled in css-modules as well. { test: /\.css$/, use: [ require.resolve('style-loader'), { ...

Encountering an issue where attempting to access the `toUpperCase` property of undefined in an *ngFor loop leads to an error

I encountered an issue when trying to specify an index in *ngFor, as I received a type error with the following message: <div class='text' *ngFor='let item of blogs; let i = index | async | filter : 'feat' : true'> Rem ...

Angular 2 routing for dynamic population in a grid system

My website is compiling correctly, however, in the Sprint dropdown menu where I have set up routing... <a *ngFor = "let item of sprint;" routerLink = "/Summary" routerLinkActive = "active"> <button *ngIf = "item.Name" mat-menu-item sty ...

Utilizing Angular 6 mergeMap for handling nested API requests

My goal is to retrieve a list of clients along with their accounts using the observe/subscribe pattern. Each client should have a list of their accounts associated with their client id. This is how I attempted it: this.httpService.getClients().subscribe( ...

AngularJS UI-Router in hybrid mode fails to recognize routes upon initial page load or reload

It appears that when using the @ui-router/angular-hybrid, routes registered within an ng2+ module are not being recognized during the initial load or reload. However, these same routes work fine when accessed by directly typing the URL. I have followed th ...

Unveiling the Mystery of Angular: Why are constructor parameters without access specifiers hidden from view outside the

When I explicitly set an access specifier for a constructor parameter, it becomes visible outside the constructor. For example: constructor(private employeResourceService:EmployeeResourceService ){ //code} ngOnInit(){ this.employeResourceService=unde ...

The type '[Images]' cannot be assigned to type 'string'

I am attempting to pass an array of objects through props, but encountered the following error: (property) images: [Images] Type '[Images]' is not assignable to type 'string'.ts(2322) ProductBlock.tsx(4, 5): The expected type co ...

Agents should only be initialized within a before function or a spec in Angular

Having trouble with my private function: private GetChargesByClient(clientId: number): Observable<any[]> { const ds = new Date(); const dateTocompare = new Date(ds.setFullYear(ds.getFullYear() - 1)); return this.getCharges(id).pipe(map(res => re ...

Webpack cannot find the specified module extension

I am facing a challenge with my project that involves both express and Angular. In this discussion, I will focus only on the express side. https://i.sstatic.net/C1blt.png When importing custom modules on the server side, I use the following syntax: impo ...