TypeScript provides some built-in types out of the box like String, Number, Boolean, any and you can also create custom types.
Unlike JavaScript, you can have strong typing support with TypeScript that gives you compile time error checking.
Strong typing can ensure that you always pass the correct number of parameters as well as the correct type of parameters to a method.
You can create a custom type by using a class or an interface.
Let's create a custom interface type named Hero:
class Hero {
id: number;
name: string;
}
You can now use this type to set a type on a method's parameter like this:
onSelect(hero: Hero): void {
}
If you pass any other value that is not of type Hero
to this method, you will have compile time error.
void
is an indication that this method does not return anything. You can return any object from this method and can also specify the same type by replacing the void keyword. Example:
onSelect(hero: Hero): boolean {
return false;
}
Overall, typescript provides good strong typing support that can save you lots of time as the error is encountered while you write code instead of finding this issue at run-time like JavaScript.
Play with this TypeScript playground here to learn more about TypeScript.
selectedHero: Heroes;
onSelect(hero: Heroes): void {
this.selectedHero = hero;
}
You will often find usage of selectedItem
in application like these which is a class member to save the selected item so that you can use it to work with it say for displaying that item or edit that item.
In this example it is selectedHero
. When user selects a hero, you assign that selected hero to your class member selectedHero
. And then this selectedHero
is used to highlight user selection in that Angular example.