Search code examples
angulartypescriptangular-services

error TS2322: Object literal may only specify known properties, and 'labels' does not exist in type


I have a problem that I can not explain.

I create an angular service with the interface implementation but it tells me that I have an error that I can not explain.

error TS2322: Type '{ labels: string[]; datasets: { data: number[]; backgroundColor: string[]; hoverBackgroundColor: string[]; }[]; }' is not assignable to type 'DataBase[]'.

Object literal may only specify known properties, and 'labels' does not exist in type 'DataBase[]'.

this my code :

Interface.ts

export interface Dashboardtwidget {
  title: string;
  widgetType: string;
  datatype: DataBase[];
}

export interface DataBase {
 labels: string[];
 datasets: {
 data: number[];
 backgroundColor: string[];
 hoverBackgroundColor: string[]
};
}

service.ts

import {Injectable} from '@angular/core';
import {Dashboardtwidget} from '../models/dashboard';


@Injectable()
 export class DashboardService {
  data: Dashboardtwidget[] = [
  {
    title: 'Widget 1',
    widgetType: 'cardStyle1',
    datatype: {
      labels: ['A','B','C'],
      datasets: [
        {
         data: [300, 50, 100],
         backgroundColor: [
          '#FF6384',
          '#36A2EB',
          '#FFCE56'
         ],
         hoverBackgroundColor: [
          '#FF6384',
          '#36A2EB',
          '#FFCE56'
        ]
       }]
    }
  }
  }

Has anyone ever had this problem and this error message?

Because I do not see where the problem comes from


Solution

  • datasets in DataBase looks like an Array type when you've declared it as an Object type.

    Change your DataBase interface to this:

    export interface Dashboardtwidget {
      title: string;
      widgetType: string;
      datatype: DataBase[];
    }
    
    interface Dataset {
      data: number[];
      backgroundColor: string[];
      hoverBackgroundColor: string[];
    }
    
    export interface DataBase {
      labels: string[];
      datasets: Dataset[];
    }
    

    Here's a Working Sample StackBlitz for your ref.