One of the key advantages of TypeScript is its built-in types such as String, Number, Boolean, and any, as well as the ability to create custom types.
Unlike JavaScript, TypeScript offers strong typing support which allows for compile time error checking.
This strong typing ensures that the correct number and type of parameters are always passed to a method.
You can define custom types using classes or interfaces in TypeScript.
For instance, let's define a custom interface named Hero:
class Hero {
id: number;
name: string;
}
This custom type can now be used to specify the parameter type of a method like this:
onSelect(hero: Hero): void {
}
If a value that does not match the Hero type is passed to this method, a compile time error will occur.
The use of "void" indicates that the method does not return anything, but you can specify a return type if needed. For example:
onSelect(hero: Hero): boolean {
return false;
}
TypeScript's strong typing support helps catch errors during development rather than at runtime, similar to JavaScript.
Experiment with TypeScript through the TypeScript playground to further your understanding.
selectedHero: Heroes;
onSelect(hero: Heroes): void {
this.selectedHero = hero;
}
It's common practice to have a class member like "selectedItem" in applications to store user selections for display or editing purposes.
In this case, it's "selectedHero" where the selected hero is assigned to the class member for highlighting user selection in an Angular example.