Typescript - variable declaration

I'm not sure if this is the place for this question, but I was told that the code review is not for this.

I'm just learning Angular 2 and Typescript, so I'm working on this next tutorial:

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

Between the third and fourth declaration of the heroes variable in app.component.ts changes:

 export class AppComponent { heroes = HEROES; } 

in

 export class AppComponent { heroes: Hero[]; } 

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

Changing the second to = actually causes the expected expression error, so I'm just trying to understand the differences between them.

+5
source share
4 answers
 heroes: Hero[]; 

does not set a value. It just defines a property with

  • name = heroes
  • type = Hero[] , which means an array of Hero
  • without assigning a value that preserves the default value of null .

With initialization, it will look like

 heroes: Hero[] = [new Hero('Spidey'), new Hero('Batman')]; 
+5
source

The difference between the two is that the first one is javascript, you assign the constant ** HEROES * to the heroes variable.

Secondly, this is a typescript thing, you say that the variable heroes will be an array of heroes, basically you define an empty variable.

This is similar to java or C # where you do something like public int myNumber in your class

+1
source

Your first understanding is correct with

 heroes = HEROES 

Now,

 heroes : Hero [ ]; 

Here Hero class of fathers with certain properties. on this line, you tell the typescript compiler that heroes variable will contain a list of objects type Hero (user-defined or user-defined type) . In the OOP world, a class is a user-defined data type, and according to this, you can declare any variable with this type.

Note: you can declare (:) any varaiable with a type, you cannot assing (=) Type (in Typescript), but you can assign a variable that Type of data .

So here you cannot use = .

Hope this helps you ...

+1
source

Just complementing @ Günter Zöchbauer,

in class / interface declarations,: after the property name is used to determine its type.

However, this can cause a little confusion when you create an object "on the fly", which in this case : marks the assignment of values:

 interface MyInterface { myBooleanProperty: boolean = false; } // ... somewhere let a = { myBooleanProperty: true }; // and to add a little more fun let b: MyInterface = { myBooleanProperty: true } 
0
source

Source: https://habr.com/ru/post/1257644/


All Articles