如题,接下来我们介绍下,ts中接口的使用。
ts中接口,接口是代码的一种规范、约束和规定,ts中接口可分为以下几类:
对象型接口 :对对象的规范
函数型接口 :对函数的规范
可索引(数组型)接口:对数组(or对象)的规范
类类型接口: 对类的规范
其他接口:泛型接口、继承接口的接口 等。
本篇,我们介绍下对象型接口。
04_interface_obj.ts
/* ts中接口 接口是代码的一种规范、约束和规定。 对象型接口 :对对象的规范 函数型接口 :对函数的规范 可索引(数组型)接口:对数组(or对象)的规范 类类型接口: 对类的规范 其他接口:泛型接口、继承接口的接口 等。 * */ //对象型接口 :对对象的规范 // // function showName(name:FullName){ // console.log("hello ,my firstName is:"+name.firstName+", and my lastName is:"+name.lastName); // // } // //FullName 是一个接口(对象型接口),规范FullName对象至少应该是怎么样的 // interface FullName{ // firstName:string; // lastName:string; // } // //showName({firstName:"Bruce",lastName:"Li"}); // var zs={ // firstName:"张", // lastName:"三", // age:22 // }; // showName(zs); //当然FullName 接口中也可以指定可选属性(?表示可选的) interface FullName{ firstName:string, lastName?:string } function showName(name:FullName){ if(name.lastName){ console.log("hello ,my firstName is:"+name.firstName+", and my lastName is:"+name.lastName); }else{ console.log("hello ,my name is:"+name.firstName); } } showName({firstName:"Bruce"}); var zs={ firstName:"张", lastName:"三", age:22 }; showName(zs); ////案例 用对象型接口封装原生ajax请求 interface Config{ type:string; //get post url:string; data?:string;//可选传入 dataType:string;//json xml等 } //原生js封装的ajax function ajax(config:Config){ var xhr=new XMLHttpRequest(); xhr.open(config.type,config.url,true); if(config.data){ xhr.send(config.data); }else{ xhr.send(); } xhr.onreadystatechange=function(){ if(xhr.readyState==4 && xhr.status==200){ console.log('请求成功'); if(config.dataType=='json'){ console.log(JSON.parse(xhr.responseText)); }else{ console.log(xhr.responseText) } } } } ajax({ type:'get', data:'name=zhangsan', url:'http://www.example.com/api', // api接口url dataType:'json' });
Copyright © 叮叮声的奶酪 版权所有
备案号:鄂ICP备17018671号-1