Angular 13 CRUD project encountering an issue: Only object types can be used to create spread types

Working on a CRUD application in Angular 13, I encountered an error with Firebase. The error message reads:

"Spread types may only be created from object types"

Below is the relevant code snippet:

export class EmployeeListComponent implements OnInit {

  constructor(private service:EmployeeService) { }
  list: Employee[] =  [];
  ngOnInit(): void {
    this.service.getEmployees().subscribe(actionArray =>{
      this.list = actionArray.map(item =>{
        return {
          id : item.payload.doc.id,
          ...item.payload.doc.data()
        } as Employee
      })
    });
  }

}

The error points to this line of code:

...item.payload.doc.data()

Answer №1

Take a look at the response type of item.payload.doc.data() in the screenshot provided.

The response type is unknown. Even if the object being received can be spread, TypeScript will display this error during compilation. You can attempt something similar to the code snippet below:

return {
  id : item.payload.doc.id,
  ...(item.payload.doc.data() as Record<string,any>)
} as Employee

I cannot guarantee whether this will fulfill the requirements of the Employee interface. Alternatively, you could try replacing Record<string,any> with Employee.

Note The code excerpt here does not show your employee service. Upon reviewing the screenshot again, it appears that Firebase allows you to specify the type when integrating with Firebase.

The

QueryDocumentSnapshot<unkown>.data
suggests that you have not specified the expected type from the Firebase integration. When using the Firebase SDK/module (in whichever way), there should be an option to define the interface you are anticipating as a generic.

If you do so, you should avoid the current issue you are facing.

It has been quite some time since I last worked with Firebase, so I want to emphasize this implementation is hypothetical, and you should refer to their documentation on where and how to declare the generic type. However, the following is a common practice.

import {Firebase} from 'firebase';
import {Employee} from './employee.interface.ts';

export class EmployeeService {
  getEmployees() {
    return Firebase.getRecords<Employee>('some/path/or/resource');
  }
}

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

Tips for effectively handling Dependency Injection when interfacing with a service that requires a component

I oversee a project in Angular that follows this specific architecture: ├── media └── src ├── app │   ├── core <-- services folder inside │   ├── data │   ├── layout │  ...

Exploring the process of dynamically updating a form based on user-selected options

I need assistance with loading an array of saved templates to be used as options in an ion-select. When an option is chosen, the form should automatically update based on the selected template. Below is the structure of my templates: export interface ...

Template containing an observable collection of observables

Since the title is not helping me achieve my goal, let me explain what I'm trying to accomplish. My objective is to show a list of items in the view, which are fetched asynchronously from the backend. The service I have has a method called fetchItems ...

Issue TS2304: Unable to locate symbol 'ITokenResponse'

I encountered this error message: Error TS2304: Unable to locate the name 'ITokenResponse'. Even after trying to import as suggested in a StackOverflow response, I encountered another error: Error TS2306: File 'C:/Repository/MAngular/sr ...

Encountered an error stating 'name' property is undefined while using @input in Angular 2

Everything seems to be set up correctly, but I'm encountering an error in the browser console that says "Cannot read property 'name' of undefined": https://i.sstatic.net/TvfEr.png This is how my media.component.ts file is structured: impo ...

Angular 8 shows an error message stating "Unknown Error" when making a REST API request

My goal is to retrieve data from the server using a REST API service. The code snippet below is from my service.ts file: getCategories(): Observable<Category> { const httpOptions = { headers: new HttpHeaders({ 'Content-Type&a ...

Displaying a portion of the chart's key in a Highcharts BarChart

I need assistance displaying a partial legend (such as min, medium, max) for the X and Y axes, along with a horizontal dashed line at the medium point of the Y axis in a HighCharts BarChart. The graph is compact on the screen, serving as a summary of multi ...

Issues arise as a result of conflicts between the dependencies of @ionic/angular, Angular 13, typescript,

Current Environment Details: ionic info Ionic: Ionic CLI : 6.18.1 (/usr/local/lib/node_modules/@ionic/cli) Ionic Framework : @ionic/angular 5.8.5 @angular-devkit/build-angular : 13.0.2 @angular-devkit/schemat ...

Executing an Angular2 Function in Unity WebGL

Currently, I am utilizing Angular2 version 2.1.2 along with a Unity visualizer created with Unity 5.5. My main requirement is to establish communication from Unity to Angular2. I had previously used a code snippet similar to the one below public void G ...

Using ES6 Template Strings for Template Binding in Angular 4

There's something I was able to easily accomplish in Vue, but for some reason, it doesn't seem to work in Angular 4: <div class="time-translate" [ngStyle]="{transform: `translate3d(${gridTranslateX}px, 0, 0)`}"> It appears that I may have ...

Combining Different Types of Errors

Can TypeScript's type system be exploited to provide additional information from a repository to a service in case of errors? I have a service that needs a port for a repository (Interface that the Repository must implement), but since the service mu ...

Creating a Dynamic Example in Scenario Outline Using Typescript and Cypress-Cucumber-Preprocessor

I have a question that is closely related to the following topic: Behave: Writing a Scenario Outline with dynamic examples. The main difference is that I am not using Python for my Gherkin scenarios. Instead, I manage them with Cypress (utilizing the cypre ...

Ionic app encountering issues with Facebook OAuth login functionality

Currently, I am implementing Facebook Auth for my Ionic app by using the Firebase module. Despite setting up the firebase module correctly initially, I keep encountering an error during the login process. It should be noted that the login function worked p ...

Angular 5 ngIfElse: How to save the outcome of a condition in a storage container

Code Snippet: <mat-icon [ngClass]='{ rotate: !users }'>refresh</mat-icon> <div *ngIf="usersObservable | async as users; else loading"> ... </div> <ng-template #loading let-users> Waiting... </ng-template> ...

Enabling universal pre-rendering results in the establishment of empty transfer-state

I have implemented Angular Universal in my application along with prerendering. The specific paths that I have set for prerendering are as follows: / /about /login Interestingly, the only path that utilizes transfer state is: /:id Upon building and run ...

Can you provide some guidance on utilizing a for loop within Angular?

Storing the values entered by the user in an input field as "values" and having another array, "existing userdetails," returned from the backend that contains all details of existing users, I am faced with the task of comparing these two sets of data. I h ...

The automated test locator in Angular using Protractor is failing to function

I am facing a challenge with my angular web application as there are some elements that are difficult to interact with. One specific element is a checkbox that needs to be checked during testing: ` <div class="row form-group approval_label"> < ...

Transferring information between screens in Ionic Framework 2

I'm a beginner in the world of Ionic and I've encountered an issue with my code. In my restaurant.html page, I have a list of restaurants that, when clicked, should display the full details on another page. However, it seems that the details for ...

Error 500 on Firebase: Issue solving "firebase" in "firebase.js" not resolved

Struggling to incorporate Firebase into my latest React project, I keep encountering the dreaded "The development server returned response error code: 500." Despite creating a firebase.js file to house my Firebase configuration details, I am at a loss as ...

Error message "Invalid 'headers' entry format" encountered while attempting to define the Last-Modified header

I'm encountering an issue while attempting to configure the Last-Modified header for my resources to ensure they are cached correctly. Upon executing firebase deploy, I am faced with the following error: FIREBASE WARNING: set at /hosting/headers/dsta ...