typescript学习之 接口

接口的作用:行为和动作的规范,对批量方法进行约束, 主要通过关键字 interface 定义接口

属性接口
interface Param { // 规定函数传入的参数是一个对象,并且必须符合以下特征
    name:string;  // 注意是用分号结束
    age:number;
}
function getInfo(info:Param):void{ // 这样就把函数的参数和定义的接口做了关联
    console.log(info.name + info.age)
}
getInfo({  // 主要就是对函数调用传入的参数进行约束,必须要符合接口的规范
    name: '张山',
    age: 24
})
可选属性接口 (ts中的可选 就需要一个问号)
interface Param {
    name:string; // 注意是用分号结束
    age?:number; // 加上问号,就是可选参数
}
function getInfo(info:Param):void{
    console.log(info.name + info.age)
}
getInfo({ // 主要就是对函数调用传入的参数进行约束
    name: '张山'
})
函数类型的接口
interface validators{
    (key:string, value:string):string
}
const createFunction:validators = function (param1:string, value:string):string{
    return param1 + value
}
console.log(createFunction('参数一'. '参数二))// 这样就相当于指定了函数的参数必须是两个,并且类型都是string,返回值业是string
可索引接口

主要对数组和对象的约束 (不常用)

interface userArr{ // 表示数组的索引为number,数组中的元素必须是string
    [index:number]:string
}
const arr:userArr = ['111', '222'];
console.log(arr[0]) // "111"
类 类型接口
interface validators {  // 表示创建的类必须要有name这个属性,并且是string,还要有work这人方法
    name: string;
    work(str:string):void
}
class Parent implements validators {
    name:string;
    constructor(name:string) {
        this.name = name
    }
    work() {
        console.log(this.name + '在干啥')
    }
}
const p = new Parent('张山');
p.work();
接口的扩展
  • 接口继承接口
interface parent {
  eate():void
}
interface child extends parent { // child接口继承parent接口
  work():void
}
class People implements child{ // 那这类People这个类中就必须要有 eate和work两个方法
  public name:string;
  constructor(name:string){
    this.name = name;
  }
  eate() {
    console.log(this.name + '在吃东西')
  }
  work() {
    console.log(this.name + '在工作')
  }
}
const peo = new People('张山');
peo.eate();
peo.work();
  • 接口的继承 和 类的继承
interface parent {
  eate():void
}
interface child extends parent { // 接口继承接口
  work():void
}
class Pub{
  public name:string;
  constructor(name:string){
    this.name = name;
  }
  study() {
    console.log(this.name + '在学习')
  }
}
class People extends Pub implements child{ // 类的继承和接口关联
  constructor(name:string){
    super(name)
  }
  eate() {
  console.log(this.name + '在吃东西')
 }
  work() {
    console.log(this.name + '在工作')
  }
}
const peo = new People('张山');
peo.eate();
peo.work();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值