TypeScript基本知识,为学习AngularJS2框架做个小铺垫

学习angularjs2框架,需要了解一些TypeScript知识点,基本了解下面这几个知识点学习AngularJS2 就够用了

1.TypeScript

1.1显示类型的定义

TypeScript类似于java和c++,允许我们显示声明的类型:

let foo : number = 42;

let 声明变量跟js里面定义var一样

1.2 any类型

TypeScript所有的类都是any的子类,如果把所有变量都声明为any类型,就是失去TypeScript编译器带来的优点,慎用any。

1.3 Enum类型

跟java里面的枚举类型一样

enum STATES {
  CONNECTING,
  CONNECTED,
  DISCONNECTING,
  WAITING,
  DISCONNECTED
};

1.4 Array类型

TypeScript中的数组和JavaScript类似。

let randomItems: any[] = [];
randomItems.push(1);
randomItems.push("foo");
randomItems.push([]);
randomItems.push({});

1.5 Function类型

如果使用函数表达式的方式把一个函数赋值给一个变量,可以如下定义:

let variable:(arg1:type1,arg2:type2,...) = >returnType

例如:

let isPrime: (n:number) => boolean = n=>{
  //body
  
}

如果采用函数声明的方式

function isPrime(n:number): boolean{
  //body
}

如果需要在对象字面量里面定义方法

let math = {
  squareRoot(n:number):number{
    //body
  }
}

如果我们定义的函数只会产生一些副作用,而不是返回一个值,那么我们可以把它定义成void函数:

let person = {
  _name :null,
  setName(name:string):void {
    this._name =name;
  }
}

1.6 定义类

class Human {
    static totalPeople = 0;
    _name : string;
    constructor(name){
      this._name = name;
      Human.totalPeople += 1;
    }
 get name(){
   return this._name;
 }
 set name (val) {
   this._name = val;
 }
 talk() {
   return 'hello ${this.name}';
 }
}

可以如下调用

let human = new Human('foo');
console.log(human._name);

1.7 访问修饰符

public 全局可访问

private 当前类内部访问

portected 当前类内部或者子类中访问

1.8 定义接口

interface Accountable {
  getIncome(): number;
}

实现这个接口

class Firm implements Accountable {
  getIncome(): number{
    //body
  }
}
class Individual implements Accountable {
  getIncome(): number{
    //body
  }
}

和java语法一样,如果实现了这个接口,那么必须实现这个接口的里面定义的所有方法。

1.9 接口继承

接口之间可以相互继承,并支持多继承

interface Accountable {
  accountNumber: string;
  getIncome():number;
}
interface Indivdual extends Accountable{
  ssn: string;
}

1.10 使用TypeScript装饰器提升表现力

class Http{
  //body
}
class GitHubApi{
  constructor (@Inject(Http) http){
    //body
  }
}

1.11 使用泛型函数

function identity<T>(arg:T){
  return arg;
}

多重泛型

let pair = new Pair<string,number>();
pair.key = "foo";
pair.value = 42;