一、 接口
1.可以用接口确保类拥有特定的结构、方法。
interface LoggerInterface{
log(arg: any): void;
}
class Logger implements LoggerInterface{
log(arg){
if(typeof console.log === "function"){
console.log(arg);
}else{
alert(arg);
}
}
}
2.还可以用来约束对象。
interface UserInterface{
name : string;
passwd : string;
}
var user : UserInterface = {
name : "",
passwd : ""
}
二、范型
作用:避免重复代码 ,还有就是代码规范吧
function<T>(class: T[], callback:(student:T, index:integer)=>void):void{
for(let i = 0; i < class.length(); i++){
callback(class[i], i);
}
}
--上面的函数就是范型函数,T是个类型
--如果不用泛型函数,类型用any也行
function(class:any[], callback:(student:any, index:integer)=>void):void{
}
--这样编译也没有什么问题,就是代码不够规范,也容易出现类型问题