Angular 财产';XYZ';类型CustomModel[]中缺少
TypeScript v2.7.2 我有以下代码片段:Angular 财产';XYZ';类型CustomModel[]中缺少,angular,typescript,typescript-typings,Angular,Typescript,Typescript Typings,TypeScript v2.7.2 我有以下代码片段: import { Component, OnInit } from '@angular/core'; import { Ingredient } from "../shared/ingredient.model"; @Component({ selector: 'app-shopping-list', templateUrl: './shopping-list.component.html', styleUrls: ['./s
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)
];
}
“共享”文件夹位于“应用”文件夹中,比导入中的(../in import)高一步。我的配料模型中包含以下内容:
代码在编译为JavaScript时肯定会运行,但TypeScript遇到了一个我无法解决的错误:
Error:(10, 3) TS2322:Type 'Ingredient[]' is not assignable to type 'Ingredient'.
Property 'name' is missing in type 'Ingredient[]'.
据我所知,我声明我需要一个数组类型的成分元素。我根据相应的类型,用两个元素启动了这个数组。我知道自定义类型数组中没有“Name”属性,但为什么它希望数组是元素,而不是数组
当构造函数参数中给出名称时,为什么会出现名称丢失的错误?
不幸的是,我不能分享我写这篇文章的课程来源。课程材料没有提及任何内容,我想这是因为代码在这个阶段按照预期编译和运行
编辑:添加了angular标记。我已将您的代码放入我在angular中创建的新项目中。我将所有内容都放在一个文件中,如下所示:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
private ing: Ingredient[] = [
new Ingredient('test', 10),
new Ingredient('test', 10)
];
constructor() {
this.ing.forEach(el => {
console.log(el);
});
}
}
export class Ingredient {
constructor(public name: string, public amount: number) { }
}
这很好用。我可以看到,在控制台中,数组的两个元素被打印出来。你能试着复制这段代码,然后也试一下吗?我知道它应该可以正常工作。实际上,您可以尝试按f12键输入“component[]”名称,以查看您使用的空闲类是否正确。也很抱歉没有把它作为一个评论发布,但我没有足够的声誉这样做 我已将您的代码放入我在angular中创建的新项目中。我将所有内容都放在一个文件中,如下所示:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
private ing: Ingredient[] = [
new Ingredient('test', 10),
new Ingredient('test', 10)
];
constructor() {
this.ing.forEach(el => {
console.log(el);
});
}
}
export class Ingredient {
constructor(public name: string, public amount: number) { }
}
这很好用。我可以看到,在控制台中,数组的两个元素被打印出来。你能试着复制这段代码,然后也试一下吗?我知道它应该可以正常工作。实际上,您可以尝试按f12键输入“component[]”名称,以查看您使用的空闲类是否正确。也很抱歉没有把它作为一个评论发布,但我没有足够的声誉这样做 我发现您的代码有一个小问题,请尝试更新以下行add'var或let'
`let ingredients : Ingredient[] = [
new Ingredient('Apples', 5),
new Ingredient('Tomatoes', 10)
];`
我想这可能会有帮助。我发现您的代码有一个小问题,您可以尝试更新下面的行add'var或let'
`let ingredients : Ingredient[] = [
new Ingredient('Apples', 5),
new Ingredient('Tomatoes', 10)
];`
我想这可能会有帮助。我做了几乎完全相同的事情,我这边没有问题。这样做很好。结果是,在保存了一些更改后,NodeJS被卡住了。NodeJS重启就足够了,但是IDE重启解决了这个问题。谢谢你的帮助!我做了几乎完全相同的事情,在我这边没有任何问题。这样做很好。结果是,在保存了一些更改后,NodeJS被卡住了。NodeJS重启就足够了,但是IDE重启解决了这个问题。谢谢你的帮助!