TypeScript 接口

介绍

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++等支持多继承请绕路)

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

官方文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

绝知芳誉亘千乡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值