In javascript, there is no required type checking, allowing you to assign variables with different types like someVar="hello"
and then someVar=true
, which is acceptable in javascript. TypeScript, on the other hand, provides type checking capabilities and other features for javascript, regardless of initialization.
=
sets the value of the variable
:
sets the type of the variable
For example:
public heroes = HEROES; // assigns value of HEROES to heroes, heroes now has an inferred type same as the type of HEROES
title = "Tour of Heroes"; // normal assignment with inferred type of 'string'
selectedHero: Hero; // just declares selectedHero with the type 'Hero'
You can define both a value and type simultaneously:
title:string = "some text"; // this means, title is of type string and has the value "some text"
If later you try title=true
, the compiler will warn you about assigning a boolean value to a string variable.
Extra
You can also set multiple types instead of just one:
title:string|boolean=true; // title is of type either string or boolean
title:"text1"|"text2"|"text3"; // (v1.8 and after) title is of type string and can have only one of the values: "text1","text2" or "text3". in other words enum type
title:any; // title is of any type.
On function declaration:
someFunction(name:string):boolean{
// the parameter 'name' is expected to be of type string in the body of this function
return true; // the return type of the function is expected to be boolean
}
Lambda Expression:
someFunction = (name:string):boolean => {
// the variable name is expected to be of type string in the body of this function
return true;
}
For more information, check out:
Typescript specs for Types
Typescript Type System