Typescript中的类

TypeScript进阶
本文介绍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

转载于:https://www.cnblogs.com/shouming/p/6562131.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值