• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

TypeScript 接口

武飞扬头像
绝知芳誉亘千乡
帮助1

介绍

TypeScript 的核心原则之一是对值所具有的结构进行类型检查。我们使用接口(Interfaces)来定义对象的类型。

基本语法

(() => {
  // 定义一个接口 给接口作为Iperson对象的类型使用
  interface Iperson {
    readonly id:number //readonly 只读属性
    name?: string // ? 可选属性
    age:number
  }
  // 定义一个接口类型的对象
  const person: Iperson = { 
    id:1,
    // name: "小明",
    age:18
  }
})()

函数类型

(() => {
  // 为了使用接口表示函数类型,我们需要给接口定义一个调用签名
  // 他就像是一个只有参数列表和返回值类型的函数定义。参数列表里的每个参数都需要名字和类型。

  // 定义一个接口作为某一个函数的类型来使用
  interface IsearchFun {
    // 定义一个调用签名
    (source: string, subString: string): boolean
  }
  // 定义一个函数 该类型就是上面定义的接口
  const searchString:IsearchFun = function (source: string, subString: string): boolean {
    return source.search(subString) > -1
  }

  console.log(searchString('231','2')) // true
})()
学新通

接口中的类 的类型

接口类的简单使用

(() => {
  // 类的类型 可以通过接口来实现
  // 定义一个接口
  interface Ifly {
    // 定义一个方法
    fly()
  }
  
  interface Iswim {
    // 定义一个方法
    swim()
  }

  // 定义一个类 这个类的类型 为接口类型 (在类中实现接口的约束)
  // Person 类实现了 Ifly,Iswim 接口
  class Person implements Ifly,Iswim {
    fly() { 
      console.log('fly方法')
    }
    swim() { 
      console.log('swim方法')
    }
  }
  
  const person = new Person
  person.fly()
  person.swim()
})()
学新通

接口的继承

(() => {
  // 类的类型 可以通过接口来实现
  // 定义一个接口
  interface Ifly {
    // 定义一个方法
    fly()
  }
  
  interface Iswim {
    // 定义一个方法
    swim()
  }

  // 定义一个类 这个类的类型 为接口类型
  // Person 类实现了 Ifly,Iswim 接口
  class Person implements Ifly,Iswim {
    fly() { 
      console.log('fly方法')
    }
    swim() { 
      console.log('swim方法')
    }
  }
  
  const person = new Person
  person.fly()
  person.swim()


  // 接口的继承
  // 定义一个接口 继承之前的接口
  interface animation extends Ifly,Iswim {}

  class Person1 implements animation {
    fly() { 
      console.log('fly方法1')
    }
    swim() { 
      console.log('swim方法1')
    }
  }

  const person1 = new Person1()
  person1.fly()
  person1.swim()
})()
学新通

个人理解
implements和extends的区别(c 等支持多继承请绕路)

继承 通过类 可以继承父类的内容 一个子类只能通过一个父类继承
实现 通过接口 可以约束子类的内容 一个子类可以通过多个接口实现
接口可以继承自其他多个接口(类似合并)

官方文档

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggheac
系列文章
更多 icon
同类精品
更多 icon
继续加载