Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular ';新';vs隐式类型_Angular_Typescript_Object - Fatal编程技术网

Angular ';新';vs隐式类型

Angular ';新';vs隐式类型,angular,typescript,object,Angular,Typescript,Object,我正在学习我的课程学习角度。在本课程中,我们将制作一个应用程序,用于显示菜谱,并允许您将菜谱中的项目添加到购物列表中。我已经创建了一个模型来描述TypeScript中的一个成分,我已经将它们放在了一个数组中 代码如下所示: ingredients: Ingredient[] = [ new Ingredient('Apples', 5), new Ingredient('Tomatoes', 3), ]; 这是模型(简短) 下面是它在组件中的使用位置: export class Sho

我正在学习我的课程学习角度。在本课程中,我们将制作一个应用程序,用于显示菜谱,并允许您将菜谱中的项目添加到购物列表中。我已经创建了一个模型来描述TypeScript中的一个成分,我已经将它们放在了一个数组中

代码如下所示:

ingredients: Ingredient[] = [
  new Ingredient('Apples', 5),
  new Ingredient('Tomatoes', 3),
];
这是模型(简短)

下面是它在组件中的使用位置:

export class ShoppingListComponent implements OnInit {
  ingredients: Ingredient[] = [
    { name: 'Apples', amt: 5 },
    { name: 'Tomatos', amt: 3 },
  ];
我的问题是:讲师使用
new
声明数组中的对象,例如:
new component('Apples',5)
,但我想知道的是,是否需要
new
关键字?
components
数组被显式类型化为component,因此数组中的任何对象都不会被强制符合component类吗?无论哪种方式,当我启动应用程序时,数据在应用程序上都显示相同。我知道键入是有效的,因为如果我将
{foo:'bar'}
放入数组,webpack将拒绝编译


new
调用构造函数和像我那样写出对象有什么区别吗?

正如Jon提到的,TypeScript使用结构类型。因此,您所做的“看起来”像是一种成分,但实际上并不是类的实例

如果您在类中添加方法或getter/setter,那么代码将中断

例如,尝试将方法添加到
成分
类:

export class Ingredient {
    constructor(public name: string, public amt: number) {}

    doubleAmount() {
      return this.amt * 2;
    }
}
您将看到数组随后生成一个键入错误

如果您这样做声明,则不会生成错误:

ingredients: Ingredient[] = [
  new Ingredient('Apples', 5),
  new Ingredient('Tomatoes', 3),
];
因此,即使您的对象“匹配”了配料类定义,并将被TS视为配料(只要它们继续匹配),它们也不是配料类的实例


有意义吗?

TS使用结构而不是名义上的键入。因此,只要您的对象符合接口,无论您是创建它还是从文本构建它,都无关紧要。但是
new
创建一个拥有方法、访问器等的类要容易得多。TL;如果你不需要一个类能提供的任何东西,那就用一个接口来代替。是的,我认为这是有道理的。它是与类型匹配的对象,但不是成分的实例。谢谢