HTML and CSS Reference
In-Depth Information
Here, numbers are typed as numbers. Because this is still JavaScript, at the end of the day, you don't have int,
float, or double, as you would find in other typed languages.
var likesGames: boolean = true;
And, you can see that you can easily type booleans, as you would expect to use the Boolean type.
Another advantage of the compiler is type inference. This allows you to declare variables without having to type
them explicitly. So, the previous code could also be done like this:
var name = "Jesse Freeman";
var age = 34;
var likesGames = true;
So long as the compiler can fully qualify what the type will be, it will automatically figure it out for you.
Now, arrays and objects can also be typed:
var myArray = any[];
As you can see, the any type is being used to define a generic array. This means that the compiler will ignore
mixing and matching of types inside of the array. You could easily type it to something specific, such as string or
number, if you knew that the contents of the array would always be the same.
var myArray:string[] = ["Jesse", "Freeman"];
TypeScript also supports classes. This is very important, because, although classes are not a native part of
JavaScript, every developer has his or her own way of making them. This could be problematic when you work in
larger teams or when you want to keep your code consistent across developers.
Let's take a look at a simple class:
class Player {
name: string;
age: number;
constructor(name: string, age: number, likesGames:boolean) { = name;
this.age = age;
this.likesGames = likesGames;
To create a new player, you would use the new constructor:
var player = new Player("Jesse Freeman", 34, true);
Likewise, the JavaScript that is generated for this class looks like this:
var Player = (function () {
function Player(name, age, likesGames) { = name;
this.age = age;
this.likesGames = likesGames;
return Player;
Search WWH ::

Custom Search