接口

对行为和动作进行规范,对批量方法也进行了约束

/**
 * 接口
 */
interface FullName {
  firstName: string
  lastName?: string         // 可选属性
}
function printName (name: FullName) {
  console.log(name.firstName + ' ' + name.lastName)
}
printName({                 // 这种写法,必须要求传参跟FullName类型完全一致
  firstName: 'Yu',
  lastName: 'Ki'
})
/**
 * 推荐写法,但是就算是这样不报错,也应该严格要求按照接口要求的参数进行书写
 */
let obj = {
  firstName: '新垣',
  lastName: '结衣',
  role: 'Wi-Fi'
}
printName(obj)              // 这种写法的话,只要obj中包含FullName要求的属性就正确

函数类型接口

对方法传入的参数还有返回值进行约束

// 加密的函数类型接口
interface encrypt {
  (key: string, value: string): string  // 规定的函数接口
}
let mayumi = {
  key: 'Mayumi',
  value: 'Wi-Fi'
}
let md5: encrypt = function (key: string, value: string): string {    // 实现函数接口
  return key + ' - ' + value
}
alert(md5(mayumi.key, mayumi.value))

可索引接口

数组约束

// 可索引接口 对数组的约束
interface UserArr {
  [index: number]: string
}
let arr: UserArr = ['a', 'b']
console.log(arr[0])             // a

对象约束

interface UserObj {
  [index: string]: string
}
let obj: UserObj = {
  name: 'Mayumi',
  role: 'Wi-Fi'
}

类类型接口

对类的约束,用法有点类似抽象类

interface Animal {
  name: string
  eat(str: string): void
}
class Dog implements Animal {
  name: string
  constructor (name: string) {
    this.name = name
  }
  eat (str: string): void {
    alert(`${this.name} is eating ${str}`)
  }
}
let me = new Dog('mayumis heart')
me.eat('mayumi')

接口继承接口

interface Human {
  sleep (): void
}

interface male extends Human {
  drink (): void
}

interface female extends Human {
  eat (): void
}

class Mistic implements male {
  name: string
  constructor (name: string) {
    this.name = name
  }
  sleep (): void {
    alert(`${this.name} is sleeping!`)
  }
  drink (): void {
    alert(`${this.name} is drinking soft drinks`)
  }
}

class Yuki implements female {
  name: string
  constructor (name: string) {
    this.name = name
  }
  sleep (): void {
    alert(`${this.name} is sleeping!`)
  }
  eat (): void {
    alert(`${this.name} is eating Mc Donalds`)
  }
}
let dk = new Mistic('Mistic')
let yk = new Yuki('Yuki')
dk.sleep()
yk.sleep()
dk.drink()
yk.eat()

你可能感兴趣的:(接口)