TypeScript 接口协议(interface)详细分析

628 阅读2分钟
  • interfacets 的含义:只声明成员方法,不做实现,定义了这个接口会有什么,但是没有告诉你具体是什么,可以用来约束一个函数,对象,以及类的结构和类型。

  • 类可以被多个接口协议约束,类也可以作为接口使用,也就是 implements 后面可以添加 单个或多个 接口与类,文章尾部有案例。

    格式:class 类名 implements 接口名, 接口名, 类名 ... {}

    例如:class Person implements Action, Info {}

  • 接口支持多继承。

    格式:interface 接口名 extends 接口名, 接口名, 类名 ... {}

    例如:interface Person extends Action, Info {}

  • 对象类型接口

    // 定义成员接口
    interface Member {
      // 成员ID
      id: number,
      // 成员名称
      name: string
    }
    
    // 定义团队接口
    interface Team {
      // 成员列表
      members: Member[]
    }
    
    // 发送团队用户 
    function sendData(team: Team) {
      team.members.forEach(item => {
        console.log(item.id, item.name)
      })
    }
    
    // 模拟数据
    let team = {
      members: [
        { id: 1, name: 'dzm' },
        { id: 2, name: 'xyq' }
      ]
    }
    
    // 发送数据
    sendData(team as Team)
    
  • 函数类型接口

    // 定义函数类型接口(两种方式)
    // 第一种
    interface Calc {
      (x:number, y:number):number
    }
    // 第二种
    // type Calc = (x:number, y:number) => number
    
    // 加法
    let add:Calc = (x, y) => { return x + y }
    // 减法
    let subtr:Calc = (x, y) => { return x - y }
    // 输出
    console.log(add(1, 2)) // 3
    console.log(subtr(4, 3)) // 1
    
  • 混合类型接口

    // 定义混合类型接口
    interface Mix {
      // 初始化构造方法
      (): void,
      // 消息
      msg: string,
      // 发送消息方法
      send(): void
    }
    
    // 初始化
    function initMix () {
      let mix:Mix = (() => {}) as Mix
      mix.msg = 'dzm'
      mix.send = () => {
        console.log(mix.msg)
      }
      return mix
    }
    
    // 使用
    let mix = initMix()
    mix.send() // dzm
    
  • 成员属性方法支持修饰符:【修饰符的详细使用】

    ?:可选修饰符,也就是可以实现可不实现。

    // 定义成员接口
    interface Member {
      // 成员ID(只读)
      readonly id: number,
      // 成员名称(必须有)
      name: string
      // 成员名称(?: 可有可无)
      age?: number
    }
    
  • 接口的实现(implements)与继承(extends)

    // 定义行动接口
    interface Action {
      // 跑起来
      run():void
    }
    
    // 定义信息接口
    interface Info {
      // 用户名称
      name: string
    }
    
    // 定义人接口,继承上面接口
    interface Person extends Action, Info {
      // 个人ID
      id: number
    }
    
    // 定义一个类,实现上面 Person 接口
    class Person1 implements Person {
      id: number
      name: string
      run(): void {
        console.log(`${this.name} 跑起来了`)
      }
    }