属性接口:对 json 的约束
function printLabel (json: { label: string }): void {
console.log(json)
}
printLabel({ label: '' })
上面的方式传 json 太繁琐
假如对批量方法传入参数进行约束
interface FullName {
firstName: string
secondName: string
}
function printName (name: FullName) {
console.log(name.firstName + '---' + name.secondName)
}
let obj = { // firstName 和 secondName 必须有,否则编译错误
firstName: '肖',
secondName: '泽',
}
printName(obj) // 肖---泽
可选属性接口
interface FullName {
firstName: string
secondName?: string
}
function getName (name: FullName) {
console.log(name)
}
getName({ firstName: 'xiao' })
实例:ajax 接口封装
interface Config {
type: string
url: string
data?: string
dataType: string
}
function ajax (config: Config) {
let xhr = new XMLHttpRequest()
xhr.open(config.type, config.url, true)
xhr.send(config.data)
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log('success')
if (config.dataType === 'json') {
console.log(JSON.parse(xhr.responseText))
}
}
}
}
ajax({
type: 'get',
data: 'name=xiaoze',
url: 'http://www.baidu.com',
dataType: 'json',
})
函数接口:对方法传入的参数,以及返回值进行约束
加密函数类型接口
interface encrypt {
// 传入参数要求 string , 返回值类型要求 string ,否则会编译错误
(key: string, value: string): string
}
let md5: encrypt = function (key: string, value: string): string {
// 加密算法忽略
return key + value
}
md5('name', ' bob') // name bob
可索引接口:数组、对象的接口(不常用)
数组
interface UserArr {
[index: number]: any
}
let arr: UserArr = ['123', 234]
console.log(arr) // [ '123', 234 ]
对象
interface UserObj {
[index: string]: any
}
let obj: UserObj = { name: 'bob', age: 21 }
console.log(obj) // { name: 'bob', age: 21 }
类类型接口:对类的约束,与抽象类有点类似
interface Animal {
name: string
eat (str: string): void
}
class Dog implements Animal { // 类必须实现接口定义属性和方法,否则编译错误
name: string
constructor (name: string) {
this.name = name
}
eat (something: string) {
console.log(`${this.name} eat ${something}`)
}
}
let dog = new Dog('tom')
dog.eat('foods') // tom eat foods
接口的扩展:继承接口
interface Animal {
eat (): void
}
interface Person extends Animal {
work (): void
}
class Programmer {
name: string
constructor (name: string) {
this.name = name
}
coding (code: string) {
console.log(`${this.name} is ${code}`)
}
}
// 必须包含 类类接口的符和子的继承
class Man extends Programmer implements Person {
name: string
constructor (name: string) {
super(name)
this.name = name
}
eat (): void {
console.log(`${this.name} is eating`)
}
work (): void {
console.log(`${this.name} is working`)
}
}
let bob = new Man('bob')
bob.eat() // bob is eating
bob.work() // bob is working
bob.coding('coding') // bob is coding