Using TypeScript v2.7.2
Check out the code snippet below:
import { Component, OnInit } from '@angular/core';
import { Ingredient } from "../shared/ingredient.model";
@Component({
selector: 'app-shopping-list',
templateUrl: './shopping-list.component.html',
styleUrls: ['./shopping-list.component.css']
})
export class ShoppingListComponent implements OnInit {
ingredients : Ingredient[] = [
new Ingredient('Apples', 5),
new Ingredient('Tomatoes', 10)
];
}
The "shared" folder is within the "App" folder, one level above (../ in import). Here is what my Ingredient model looks like:
export class Ingredient {
constructor(public name: string, public amount: number) {}
}
The JavaScript output of this code works fine, but when working with TypeScript I encounter an error that seems puzzling:
Error:(10, 3) TS2322:Type 'Ingredient[]' is not assignable to type 'Ingredient'.
Property 'name' is missing in type 'Ingredient[]'.
Even though I specified an array containing elements of type Ingredient and initialized it correctly, why does TypeScript expect the array itself to have a 'name' property instead of assuming it as an array?
Why is there an error regarding the missing 'name' property, when it is clearly defined in the constructor parameter?
I'm unable to provide the source material of the Udemy course I was following for this exercise. The course continues without addressing this issue, probably because the code compiles and functions smoothly at this stage.
Edit: Included Angular tag for reference.