环境:Angular 5+
来源:https://angular.io/tutorial
在 heroes.component.ts
类中有一个带冒号的赋值,如下所示:
export class HeroesComponent implements OnInit {
heroes: Hero[];
但是在 app.component.ts
类中有一个带等号的赋值:
export class AppComponent {
title = 'app';
}
为什么这让我感到困惑?
最佳答案
在这段代码中 heroes: Hero[];
没有任何东西被分配给 var heroes
,但是你声明它是一个 Hero 的数组
(目前它是 undefined
)。
现在,在这段代码 title = 'app';
中,您将字符串 'app'
分配给 var title
,因为 typescript 编译器可以推断 'app'
是一个字符串,所以不需要指定它 (title: string = 'app';
),在heroes
的情况,编译器不知道将分配给 var 的内容,除非您通过“告诉”: Hero[]
来指定它(它是一个数组英雄
)
关于英雄 Angular 之旅 : Why is one assigned with colon and another by equal signs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50419455/