Search code examples
angulartypescript

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.


Solution

  • 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')];