20160111

Tips

  1. 打开 .iso 文件,右键 -> 资源管理器,不能解压文件!

TypeScript 学习

TypeScript 的基本类型

For programs to be useful, we need to be able to work with some of the simplest units of data: numbers, strings, structures, boolean values, and the like. In TypeScript, we support much the same types as you would expected in JavaScript, with a convenient enumeration type thrown in to help things along.

我们需要一些简单的数据单位。numbers, strings, structures, boolean 值。和JavaScript提供几乎相同的数据类型,此外还提供了枚举类型方便使用。

  • Boolean
    The most basic datatype is the simple true/false value, which JavaScript and TypeScript (as well as other languages) call a ‘boolean’ value.
    提供简单的 true 或者 false。
1.var isDone: boolean = false;
  • Number
    As in JavaScript, all numbers in TypeScript are floating point values. These floating point numbers get the type ‘number’.
    像是在 JavaScript 中,所有在 TypeScript 中的数字都是浮点型的。 除了支持十进制和十六进制字面量,Typescript还支持ECMAScript 2015中引入的二进制和八进制字面量。
1.var height: number = 6;
  • String
    Another fundamental part of creating programs in JavaScript for webpages and servers alike is working with textual data. As in other languages, we use the type ‘string’ to refer to these textual datatypes. Just like JavaScript, TypeScript also uses the double quote (“) or single quote (‘) to surround string data.
    和其他语言一样,用 string 表示文本数据类型,用 “” 或 ” 包围数据。
1.var aString: string="hello world";

( 中文版 )你还可以使用模版字符串,它可以定义多行文本和内嵌表达式。 这种字符串是被反引号包围(` ),并且以${ expr }这种形式嵌入表达式

1.let name: string = `Gene`;
2.let age: number = 37;
3.let sentence: string = `Hello, my name is ${ name }.
4.
5.I'll be ${ age + 1 } years old next month.`;

这与下面定义sentence的方式效果相同:

1.let sentence: string = "Hello, my name is " + name + ".\n\n" +"I'll be " + (age + 1) + " years old next month.";
  • Array
    TypeScript, like JavaScript, allows you to work with arrays of values. Array types can be written in one of two ways. In the first, you use the type of the elements followed by ‘[]’ to denote an array of that element type:
1.var newArray: number[]=[1,2,3];
2.// 还有用 Array 构造的一种
  • Enum
    A helpful addition to the standard set of datatypes from JavaScript is the ‘enum’. Like languages like C#, an enum is a way of giving more friendly names to sets of numeric values.
    枚举可以为一组数值赋予友好的名字。
1.enum Color {Red, Green, Blue};  // 定义了一个枚举 
2.var c: Color=Color.Green; // 将变量声明为枚举类型,并赋值

By default, enums begin numbering their members starting at 0. You can change this by manually setting the value of one its members. For example, we can start the previous example at 1 instead of 0:
默认情况下,枚举从 0 开始编号, 也可以手动改变开始的数值,下面的例子就是从 1 开始编号。

1.enum Color {Red=1, Green, Blue};
2.var c: Color=Color.Green; // 2

Or, even manually set all the values in the enum:
也可以手动设置所有的枚举值

1.enum Color {Red=1, Green=2, Blue=4};
2.var c: Color=Color.Green;

A handy feature of enums is that you can also go from a numeric value to the name of that value in the enum. For example, if we had the value 2 but weren’t sure which that mapped to in the Color enum above, we could look up the corresponding name:
枚举的一个便利是可以根据枚举值得到它的名字。就像下面知道值为2,但是并不确定对应的名字,我们可以得到相关的名字

1.enum Color {Red=1, Green=2, Blue=4};
2.var c: string=Color[2]; // Green
  • Any
    We may need to describe the type of variables that we may not know when we are writing the application. These values may come from dynamic content, eg from the user or 3rd party library. In these cases, we want to opt-out of type-checking and let the values pass through compile-time checks. To do so, we label these with the ‘any’ type:
    用来描述暂时不知道类型的变量。这些值可能来自动态的内容,比如来自用户或第三方代码库。在这些情况下,我们希望在编译时进行检查而不是用类型检查器对这些值进行检查。我们可以用 any 来标记这些变量。
1.var notSure: any=4;
2.notSure= "maybe a string instead";
3.notSure=false; // finally is a boolean

The ‘any’ type is a powerful way to work with existing JavaScript, allowing you to gradually opt-in and opt-out of type-checking during compilation.
在对现有 JavaScript 进行改写时,any 是非常有用的。它可以让你选择包含或移除类型检查
The ‘any’ type is also handy if you know some part of the type, but perhaps not all of it. For example, you may have an array but the array has a mix of different types:
但你只知道一部分数据类型时,any 也是十分有用的,比如说你有一个数组,数组中有不同类型的变量。

1.var list: any[]=[1,true,"hello"];
2.list[1]=100;
  • Void
    Perhaps the opposite in some ways to ‘any’ is ‘void’, the absence of having any type at all. You may commonly see this as the return type of functions that do not return a value:
    any 和 void在某种程度上相反,他没有表示任何类型。你可以看到当一个函数不返回任何值时返回的是 void 。
1.function warnUser(): void{
2. alert("this is my warning message");
3.}

Interfaces

One of TypeScript’s core principles is that type-checking focuses on the ‘shape’ that values have. This is sometimes called “duck typing” or “structural subtyping”. In TypeScript, interfaces fill the role of naming these types, and are a powerful way of defining contracts within your code as well as contracts with code outside of your project.
TypeScript的核心原则就是值所拥有的 shape 进行类型检查。这有时被称为 “duck typing” 或 “structural subtyping”。在 TypeScript 中,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。

  • Our First Interface
    The easiest way to see how interfaces work is to start with a simple example:
1.function printLabel(labelledObj: {label: string}) {
2. console.log(labelledObj.label);
3.}
4.
5.var myObj = {size: 10, label: "Size 10 Object"};
6.printLabel(myObj);

里面的 {label: string} 就相当于一个接口。
然后 myObj 实现了这个接口?
重写上面的例子:

1.interface LabelledValue {
2. label :string;
3.} // 定义一个接口,里面的属性 label 是 string 类型
4.function printLabel(labelledObj: labelledValue){
5. console.log(labelledObj.label);
6.} // 定义函数,参数是那个接口,输出接口中的属性值
7.var myObj={size: 10,label: "hello world"}; // 定义对象,实例化接口?
8.printLable(myObj);

类型检查器不回去检查属性的顺序。
需要注意的是,我们在这里并不能像在其它语言里一样,说传给printLabel的对象实现了这个接口。我们只会去关注值的外形。 只要传入的对象满足上面提到的必要条件,那么它就是被允许的。

  • Optional Properties
    Not all properties of an interface may be required. Some exist under certain conditions or may not be there at all. These optional properties are popular when creating patterns like “option bags” where the user passes an object to a function that only has a couple properties filled in.
    不是接口中的所有属性都是必须的。一些在特定情况下需要一些根本不存在。像给函数传入的参数对象中只有部分属性赋值的情况。
1.interface SquareConfig{
2. color?: string;
3. width?: number;
4.}
5.function createSquare(config: SquareConfig):{color: string,area: number}{
6. var newSquare={color:"white",area:100};
7. if(config.color){
8. newSquare.color=config.color;
9. }
10. if(config.width){
11. newSquare.area=config.width * config.width;
12. }
13. return newSquare;
14.}
15.createSquare({color: "black"});

带有可选属性的接口与普通的接口定义差不多,只是在可选属性名字定义的后面加一个 ? 符号。
可选属性的好处之一是可以对可能存在的属性进行预定义,好处之二是可以捕获引用了不存在的属性时的错误。 比如,我们故意将createSquare里的color属性名拼错,就会得到一个错误提示:

JavaScript 中函数执行例子

1.for (var i = 0; i < 10; i++) {
2. setTimeout(function() {console.log(i); }, 100 * i);
3.}
4.// 10 10 10 10 10 10 10 10 10 10 (有换行)

setTimeOut在若干秒之后执行一个函数,并且是在 for 循环结束后。在 for 循环结束后 i 的值为 10 ,座椅每一次打印出来的值均为 10。想让里面的函数立即执行得到想要的结果可以像下面这么写:

1.for (var i=0;i<10;i++){
2. (function(i){
3. setTimeOut(function(){
4. console.log(i);
5. },100*i);
6. })(i);
7.}

用 (function(){})() 的形式让函数立即执行。
用 let 来声明可以避免这个问题,直接按上面的写法就可以了。