一、接口
接口就是一套规范,当很多的类型具备相同的特征或者属性时,我们可以将这些特征和属性单独抽离成一个接口,让这些类对这个接口(规范)进行实现
class Dog{ eat(){ console.log("骨头"); } run(){ console.log("狗跑"); }}class Cat{ eat(){ console.log("鱼"); } run(){ console.log("猫跑"); }}//只要是动物类都要实现eat()和run()方法
1-1 类类型接口
interface Animal{ eat():void; run():void;}/* 接口就是一套规范,当很多的类型具备相同的特征或者属性时,我们可以将这些特征和属性单独抽离成一个接口,让这些类对这个接口(规范)进行实现*/class Dog implements Animal{ eat():void{ console.log("骨头"); } run():void{ console.log("狗跑"); }}class Cat implements Animal{ eat():void{ console.log("鱼"); } run():void{ console.log("猫跑"); }}/* 1、那么一个类实现某个接口之后,必须对接口中的属性和方法进行重写 */
1-2 属性接口
interface Params { url: string, method: string, data?: Object //?可传可不传}/* 属性接口:对方法的参数的约束 *//* function http (obj:{url:string,method:string}):void{ console.log(obj);}http({url:"top250",method:"get"}) */function http(d: Params): void { console.log(d);}http({ url: "top250", method: "get",})http({ url:"login", method:"post", data:{ usename:"lisi", pwd:123 }})
1-3 函数类型接口
interface encrypt{ /* 设置函数的参数和返回值的类型 */ (key:string,value:string):string}var md:encrypt = function(key:string,value:string):string{ return key+value}console.log(md("key","lisi"));
1-4 接口的继承
class Animal{ name:string; age:number;}interface Dog extends Animal{ eat(str:string):void}class WolfDog implements Dog{ name:string; age:number; eat(str:string):void{ console.log(str); } constructor(name:string,age:number){ this.name = name; this.age = age; }}var w:WolfDog = new WolfDog("狗",8)
二、泛型
/* 泛型:任意类型 */var str:any = "hello";str = 2021;/* 劣势:放弃了类型检查 *//* 既要任意类型又要类型检查 */// 1、有类型检查,只能放置特定数据类型function getData(msg:string){ console.log(msg);}// 2、可以传入任意类型,但没有类型检查function test(msg:any){ console.log(msg);}
2-1 设置泛型
/* 泛型好处:既有类型检查又可以传入任意类型 */function getMsg<T>(msg:T){ console.log(msg);}getMsg<string>("hello")getMsg<Number>(2021)
2-2 泛型函数
function getStr<T>(msg:T){ console.log(msg);}getStr<string>("hello");getStr<object>({name:"lisi"});
2-3 约束泛型
function echoWithArr<T>(arg:T []){ console.log(arg);}echoWithArr<string>(["html"]);echoWithArr<number>([1234]);/* 约束泛型:使用接口对泛型进行了拓展 */interface len{ length:number;}function getLength<T extends len>(arg:T){ console.log(arg.length);}getLength<string>("hello");getLength({length:10});getLength<Array<number>>([1,2,3]);
2-4 泛型类
class NumList<T>{ public list:Array<T> = []; add(val:T){ this.list.push(val); }}var nums = new NumList<number>();nums.add(1);nums.add(2);console.log(nums);var strs = new NumList<string>();strs.add("html")strs.add("css");console.log(strs);
2-5 泛型接口
A 对象类型接口
interface attrs<T,U>{ name:T, age:U}var obj:attrs<string,number> = {name:"lisi",age:10}