接口(interface)

typescript-logo.jpg

什么是接口

接口是一系列抽象方法的声明,是一些方法特征的集合,这些方法都是抽象的,需要由具体的类实现。其实就是一些共有的属性和方法,为了方便管理而已。

// 定义
interface interface_name {
    
}

牛刀小试

interface labelValue {
    label: string  
}
function printLabel(labelObj: labelValue) {
    console.log(labelObj.label)
}
let myObj = {size: 10, label: 'this is string'}
printLabel(myObj)

属性可选

有的时候我们需要属性是可选的

interface SquareConfig {
    color?: string;
    width?: number;
}
function creatSquare(config: SquareConfig): {color: string; area: number} {
 let newSquare = {color: 'red', area: 100}
 if (config.color) {
    newSquare.color = config.color
 }
 if (config.width) {
    newSquare.area = config.width * config.width
 }
 return newSquare
}
let mySquare = creatSquare({color: 'green'})

属性只读

当我们需要有的属性只能是创建的时候才能改变其值时,可以使用readonly

interface Point {
    readonly x: number
    readonly y: number
}
let p1: Point = {x: 10, y: 20}
p1.x = 30

// Cannot assign to 'x' because it is a read-only property.

typescript还有一个ReadonlyArray<T>,数组创建后将无法修改任何值

let num: number[] = [1, 2, 3]
let cop: ReadonlyArray<number> = num
cop[0] = 12 // Index signature in type 'readonly number[]' only permits reading.
cop.push(5) // Property 'push' does not exist on type 'readonly number[]'
cop.length = 20 // Cannot assign to 'length' because it is a read-only property

函数类型

接口除了可以用来描述普通对象,还可以用来表示函数类型,参数列表的每个参数都需要名字和类型

interface searchFunc {
    (source: string, subString: string): boolean
}
let mySearch: searchFunc
// 函数的参数名不需要和接口中定义的名字相匹配
mySearch = function (source: string, sub: string) {
    let result = source.search(sub)
    return result > -1
}

可索引的类型

接口中可像JavaScript中数组(a[5])或者对象(obj['aa'])那样,可通过索引获得

interface StringArr {
    [index: number]: string
}
let myArr: StringArr
myArr = ['tom', 'jerry']
let myStr: string = myArr[0] // myStr === 'tom'

ps: 索引支持两种索引类型: string和number,但是其实当时用number作为索引的时候,JavaScript会把其转为string来去索引对象

interface NumberDictionary {
  [index: string]: number;
  length: number;    // 可以,length是number类型
  name: string       // 错误,`name`的类型与索引类型返回值的类型不匹配
}

实现接口

interface ClockInterface {
  currentTime: Date
  setTime(d: Date)
}

class Clock implements ClockInterface {
  currentTime: Date
  setTime(d: Date) {
    this.currentTime = d
  }
  constructor(h: number, m: number) {}
}

接口继承

interface Person {
  age: number,
  name: string
}

interface Boy extends Person {
  hasBasketball: boolean
}

let boy = <Boy>{}
boy.age = 25
boy.hasBasketball = false
boy.name = 'chris byrant'

接口混合类型

接口可以同时给对象和函数使用

interface Counter {
  (start: number): string
  interval: number
  reset(): void
}

function getCounter(): Counter {
  let counter = <Counter>function (start: number) {}
  counter.interval = 123
  counter.reset = function () {}
  return counter
}

let c = getCounter()
c(10)
c.reset()
c.interval = 5.0

接口继承类

接口继承类的时候,就好像接口声明了所有类中的成员,接口会继承类的private和protected成员,这种情况下,接口只能被这个类或者其子类所实现。

class Control {
  private state: any
}
interface SelectableControl extends Control {
  select(): void
}

class Button extends Control implements SelectableControl {
  select () {}
}

class Image implements SelectableControl {
  select () {}
}
// Class 'Image' incorrectly implements interface 'SelectableControl'.
//  Property 'state' is missing in type 'Image' but required in type 'SelectableControl'.ts(2420)
//  demo1.ts(149, 11): 'state' is declared here.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容