10-TypeScript中的接口

接口是一种规约的约定,从接口继承的类必须实现接口的约定。在高级开发中,通常接口是用于实现各种设计模式的基础,没有接口,设计模式无从谈起。

定义接口:

interface ILog{
    recordlog():boolean;
}

类从接口继承:

class Log4Net implements ILog{
    public recordlog():boolean{
        try{
            console.log("log4net has been recored");
            return true;
        }
        catch(e) {
            console.log(e.message);
            return false;
        }
    }
}

类的调用:

var log=new Log4Net();
log.recordlog();

另外接口也可以作为方法的参数类型,在具体实现时,就可以传入任何从接口继承的类的实现。

接口定义:

interface IStudent{
    Name:string;
    Age:number;
}

类的定义与方法:

class MiddleSchoolStudent{
    constructor(public student:IStudent){
    }
    public GetMSSInfo(){
        console.log(this.student.Name+" "+this.student.Age);
    }
}

调用:

var mss=new MiddleSchoolStudent({
    Name:"caojian",
    Age:37
});
mss.GetMSSInfo();

欢迎加入QQ群讨论:573336726