Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - variables declaration

I'm not sure if this is the place for this question, but I've been told code review is not the place for it.

I'm just learning Angular 2 and Typescript, so am working through this following tutorial:

https://angular.io/docs/ts/latest/tutorial/toh-pt4.html

Between part three and four, the declaration of the heroes variable in the app.component.ts changes from:

export class AppComponent {
    heroes = HEROES;
}

to:

export class AppComponent {
    heroes: Hero[];
}

I understand the first one sets it to a constant of heroes array but why does the second one use a colon and not just set it to an empty array?

Changing the second one to an = actually throws an expression expected error so basically I'm just trying to understand the differences between the two.

like image 390
Pete Avatar asked Oct 03 '16 12:10

Pete


1 Answers

heroes: Hero[];

doesn't set it to a value. It just defines a property with

  • name = heroes
  • type = Hero[] which means array of Hero
  • without assigning a value which keeps it at default value null.

With initialization it would look like

heroes: Hero[] = [new Hero('Spidey'), new Hero('Batman')];
like image 198
Günter Zöchbauer Avatar answered Sep 21 '22 12:09

Günter Zöchbauer