Original link: https://leanpub.com/essentialtypescript/read#introduction
1. What is typescript.
Typescript is a superset of JS, it adds a static type of support to JS.
Read a paragraph of JS code:
var bill = {
name: "Bill",
Quack:function () {
document.write ("quack!");
}
function Sayquack (target) {
target.quake ();
}
Sayquack (Bill);
This code will run wrong because, in Sayquack (target), Target.quake () should be written as Target.quack ().
Because JS is a dynamic type language, it will not be an error until the program runs to this line. The static type language has a compilation process. The compiler will help us discover this type of error.
Typescript provides a compiler (TSC) that converts code written by typescript into JS code.
2. Version and History of JavaScript
Operating system version, browser version, JS version, bla bla bla will always haunt every developer.
This page can look at the compatibility statistics for a new version of the JavaScript language on various platforms: http://kangax.github.io/compat-table/es6/
With TSC (Typescript Transpiler), we can casually use the new language features provided by ES6 without regard to system compatibility issues. Because the TSC can be used to convert the high version of JS code to a lower version of the JS code.
3. First Typescript procedure
Typescript website provides a playground page, so that we do not install the TSC can also compile, run Typescript code: https://www.typescriptlang.org/play/index.html
3.1. Enter the following code in the playground:
function speak (value) {
document.write (value);
}
var greeted = "World";
var greeting = "Hello,";
var Whattosay = greeting + greeted;
Speak (Whatosay);
Attention:
1. You can see a red curve below the last line, which is the wrong hint, because the Whatosay is spelled incorrectly.
2. Mouse hover in any variable, function above, you can see its definition.
3. The playground right area shows the compiled JS code.
3.2. String vs. number
To modify the code:
var greeted = 1;
var greeting = 20;
Output: 21
The code above is meant to connect two strings together and output to a Web page. However, when greeted and greeting become number types, output is the sum of two numbers.
3.3. function parameter type declaration
To speak () plus the parameter type declaration: Speak (Value:string)
Speak (Whattosay); There is also a red curve, because the compiler considers the function's argument type to be wrong.
3.4. Variable type declaration
Add string type to Whattosay:
var whattosay:string = greeting + greeted;
3. 5. function return value type declaration
function speak (value:string): string {
document.write (value);
return value;
}