1.接口类型
接口的作用:定义标准
1.1属性接口
对json进行约束
// 对json进行约束
interface info{
firstName:string,
secondName:string
}
function print(info:info):void{
console.log(info.firstName+info.secondName)
}
let a={
age:20,//可以多传值,不可少传值
firstName:"李",
secondName:"四"
}
print(a)//李四
1.2可选属性接口
// 对json进行约束
interface info{
firstName:string,
secondName?:string//可选参数
}
function print(info:info):void{
console.log(info.firstName+info.secondName)
}
let a={
age:20,
firstName:"李",
}
print(a)//李undefined
示例1:
//接口
interface Config{
type:string,
url:string,
data?:string,
dataType:string
}
//定义ajax方法
function ajax(config:Config){
var xhr = new XMLHttpRequest();
xhr.open(config.type,config.url,true)
xhr.send(config.data)
xhr.onreadystatechange=function(){
if(xhr.readyState==4&& xhr.status==200){
console.log("yes")
if(config.dataType==="json"){
console.log(JSON.parse(xhr.responseText))
}else{
console.log(xhr.responseText)
}
}
}
}
//调用
ajax({
type:"get",
data:"zs",
url:"http://localhost:8090/hello/getAllInfo",
dataType:"json"
})
1.3函数类型接口
// 约束方法传入参数
interface encrypt{
(key:string,value:string):string;
}
let des:encrypt=(key,value):string=>{
return key+value
}
console.log(des("123","456"))//123456
1.4可索引接口
对数组约束
interface userArr{
[index:number]:string
}
let arr:userArr=["122","2333"]
console.log(arr[0])//122
对对象的约束
interface userArr{
[index:string]:string
}
let arr:userArr={
name:"123",
age:"20"
}
console.log(arr.name)//123
1.5类类型接口
与抽象类类似,这里是实现方法,抽象方法属于继承
interface Animal{
name:string,
eat(food:string):void
}
class Dog implements Animal{
name: string;
constructor(name:string){
this.name=name
}
eat(food: string): void {
console.log(`${this.name}吃${food}`)
}
}
class Cat implements Animal{
name: string;
constructor(name:string){
this.name=name
}
eat(food: string): void {
console.log(`${this.name}吃${food}`)
}
}
let d =new Dog("小黑")
d.eat("狗粮")//小黑吃狗粮
let c= new Cat("小花")
c.eat("老鼠")//小花吃老鼠
2.接口扩展
2.1接口继承
interface Animal{
eat():void
}
interface Person extends Animal{
work():void
}
//父类
class Programmer{
name:string
constructor(name:string){
this.name=name
}
coding(code:string){
console.log(`${this.name+code}`)
}
}
//子类
class Chinese extends Programmer implements Person{
constructor(name:string){
super(name)
}
eat(){
console.log(`${this.name}吃炸鸡`)
}
work(){
console.log(`${this.name}在上班`)
}
}
let c= new Chinese("小李")
c.eat()//小李吃炸鸡
c.work()//小李在上班
c.coding("写ts代码")//小李写ts代码
总结
ts的接口提供了一种标准,既可以约束方法、对象、数组,也可以约束类