TS之接口的使用

接口用于描述一个类或者一个对象的结构,描述他们的属性和方法,所以接口可以当做一个类的声明

interface

对象定义

我们使用interface来定义一个接口,定义的方法全部为抽象方法,必须重写

interface myInterface{
    name:string,
    age:number
}

interface myInterface{
    sex:"male"|"female",
    // sayName:()=>void
    sayName():void
}

const person:myInterface = {
    name:"Jim",
    age:18,
    sex:"male",
    sayName(){
        console.log(this.name);
    }
}

console.log(person);
  1. 接口可以定义相同的名字,最终还是一个接口,如案例中也可以写成
interface myInterface{
    name:string,
    age:number,
    sex:"male"|"female",
    sayName():void
}

类定义

一般我们使用implements关键字来使用接口

class Person implements myInterface{
    name: string;
    age: number;
    sex: "male" | "female";
    sayName(): void {
        console.log(this.name);
    }
}

数组定义

接口也可以定义数组,定义属性名的时候,要用index

interface Obj {
    [propName:string]:any
}

interface myList {
    [index:number]:Obj
}

const arr:myList = [
    {name:"黑猫警长"}
]

接口的继承

使用extends来进行接口的继承,且后可以跟多个接口,实现多重继承

interface Obj {
    [propName:string]:any
}

interface myInterface{
    name:string,
    age:number
}

interface IPerson extends myInterface,Obj{
    sex:"male"|"female",
    sayName():void
}

class Person implements IPerson{
    name: string;
    age: number;
    sex: "male" | "female";
    hobby:"read"|"write"
    sayName(): void {
        console.log(this.name);
        
    }
}

菜鸟教程

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值