Angular Object literal may only specify know prope

2020-08-11 10:41发布

问题:

I'm starting out with Angular and running into an error.

.../mocks.ts(9,4): Type '{"id": number; "name": string; "description": string; "inStock": number; "price": number; "featu...' is not assignable to type 'CarPart[]. Object literal may only specify known properties, and '"featured"' does not exist in type 'CarPart'.

My code:

car-part.ts

export class CarPart {
    id: number;
    name: string;
    description: string;
    inStock: number;
    price: number;
    featured: boolean;
}

mock.ts

import { CarPart } from './car-part';

export const CARPARTS: CarPart[] = [{
    "id": 1,
    "name": "Super Tires",
    "description": "These tires are the very best",
    "inStock": 5,
    "price": 299.99,
    "featured": false //Line 9
  }, 
  {
    "id": 2,
    "name": "Reinforced Shocks",
    "description": "Shocks made of kryptonite",
    "inStock": 4,
    "price": 500.50,
    "featured": false
  },
  {
    "id": 3,
    "name": "Padded Seats",
    "description": "Super soft seats for a smooth ride",
    "inStock": 0,
    "price": 333.33,
    "featured": true
  }];

car-parts.component.ts

import { Component, OnInit } from '@angular/core';
import { CarPart } from './car-part';
import { CARPARTS } from './mock';

@Component({
  selector: 'car-parts',
  templateUrl: './car-parts.component.html',
  styleUrls: ['./car-parts.component.css']
})
export class CarPartsComponent implements OnInit {

  constructor() { }

  carParts: CarPart[];

  totalCarParts(){
    let sum = 0;

    for(let carPart of this.carParts){
        sum += carPart.inStock;
    }
    return sum;
  }

  ngOnInit() {
    this.carParts = CARPARTS;
  }

}

when I remove "featured" from both mock.ts and car-part.ts it is fine, no error. If I add it or any other name or type, it wont work... Can someone explain this?

回答1:

I restarted the Angular CLI server (Ctrl+C > ng serve). Compiled without problems...

Evidence that "Have you tried turning it off and on again" is still relevant. Thanks for the time looking at the problems Tim and Max



标签: angular