Pete Pete - 21 days ago 4x
TypeScript Question

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:

Between part three and four, the declaration of the

variable in the
changes from:

export class AppComponent {
heroes = HEROES;


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.

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