Typescript中的类

typescriptclass声明

class Person{
    constructor(){
}
     name;
     eat(){}      
}

属性和方法有三种修饰符:private,public,protected

private:只能类内部访问;

public:类内部和外部都可引用;

protected:只能有类的内部和它的子类访问

constructor:类的构造函数,在类被实例化时仅被调用一次,类外部无法使用

类的继承

类的继承有两个关键字:extendssuper

extends:用来声明类的继承关系,表示的关系

class Employee extends Person{
   constructor(name:string,code:string){
     super(name);
     this.code = code;
}
   code:string;
}

Employee类具有Person类的所有属性和方法;

super:调用父类的构造函数或方法

泛型是参数化的类型,用以限定集合的内容

var workers:Array<Person>=[];
workers[0] = new Person("zhangsan");
workers[1] = new Employee("lisi","1");

接口

声明属性的作用

interface Phone{
    width:number;
    height:number;
}

class Iphone{
    constructor(public config:Phone);
}

var p = new Iphone({
      width:15,
      height:15
})

声明方法的作用

interface Animal{
   eat(); 
}

/*implements是实现接口的方法,不实现会报错*/
class Sheep implements Animal{
   eat(){
   console.log(" i eat something");
}
}

模块

一个文件就是一个模块

export:向外部暴露那些属性和方法;

import:需要其他文件提供什么属性和方法;

注解

注解是为程序的元素(类、方法、变量)加上更直观更明了的说明,这些说明与程序的业务逻辑无关,而是供指定框架或工具使用

例如:用angular2写的程序

@Component({
   selector:'app-root',
   templateUrl:'./app.component.html',
   styleUrls:['./app.component.css']
})

类型定义文件

类型定义文件用来帮助开发者在typescript中使用已有的javascript开发工具包,如:jquery

类型定义文件的安装:使用typings工具

https://www.github.com/typings/typings