Angular2 tour of heroes - What does the colon in onSelect(hero: Hero) mean?

When you type 'hero', it will assume it has the type 'any'. When you say hero: Hero, you delimit the type of the variable to a 'Hero', which means the function will only accept parameters of the type Hero or abstractions of it.

EDIT: for the void part, this is the return type of your function. Void means it will return nothing.

EDIT2:

selectedHero: Hero

OnSelect(hero: Hero): void{
    this.selectedHero = hero;
}

so the 'selectedHero: Hero' part you define a variabel 'selectedHero' of the type 'Hero'.

The you define your function 'OnSelect', which accepts a parameter 'hero' of the type 'Hero'. 'hero' will be the name you use to access the parameter in the function 'OnSelect'.

The function returns void, which means it returns nothing, and just does what is stated in the function.

the part this.selectedHero = hero; is trickier. Above in your component you defined a Hero variable with the name 'hero'. It is outside of the function's scope. 'this' refers to the component class you are in, it's a keyword used to access it. So to access a variable which is outside of your function, but still in your object, you use the keyword 'this'.

Ok so when you click a hero, the OnSelect function gets triggered and you pass on the hero you just clicked ( the hero: 'Hero'). What you then do is set the hero of your current object ( this.selectedHero ) equals to the hero you just clicked ( hero: Hero ).

Every time you click on a hero, it will replace the selectedHero with the one you clicked.

PS: My explanation of the 'this' keyword is made as abstract possible to comprehend, I know there's a lot more to it then i explained, but this was for the sake of the person asking, as he is new to developing.


Syntax is:

methodName(variable: Class): returnType {
    // your code here
}

EDIT: Check out the typescript documentation here.


In typescript , it indicates the type of Hero, which is of type object 'Hero'.

Where Hero is a class,

export class Hero {
    id: number;
    name: string;
}


onSelect(hero: Hero){}