接口

接口: 行为和动作的规范,对批量方法进行约束

属性接口

传入对象的约束

// 常规的属性约束
function printLabel(label: string):void {}
printLabel('label字符串')

function printLabel2(labelInfo: {label: string}):void {}
printLabel2({label: 'label字符串'})
// 使用接口
interface FullName {
    firstName: string;
    secondName: string;
}
function getName(name: FullName):void {
    console.log(name.firstName) // z 
    console.log(name.secondName) // y 
}
getName({firstName: 'z', secondName: 'y'})

可选属性接口

interface FullName2 {
    firstName: string;
    secondName?: string; // 可选属性
}
function getName2(name: FullName2):void {
    console.log(name.firstName) // z 
}
getName2({firstName: 'z'})

封装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')
        }
    }
}
ajax({
    type: 'get',
    url: 'http//:www.baidu.com/',
    dataType: 'json'
})

函数类型接口

函数类型接口 对方法传入的参数 以及 返回值进行约束 批量约束

interface Encrypt {
  (key: string, value: string): string
}
let md5:Encrypt = function (key: string, value: string):string {
    return key + 'is' + value
}
console.log(md5('name', 'zy')) // nameiszy

可索引接口(不常用)

// 可索引接口对数组的约束
interface UserArr {
    [index: number]: string
}
var arr:UserArr = ['zy', 'is']

// 可索引接口对对象的约束
interface UserArr2 {
    [index: string]: string // 索引和值的类型都是string
}
var arr2:UserArr2 = {age: '23'}

类类型接口

interface Animal2 {
    name: string;
    run(str:string):void;
}
class Dog implements Animal2 {
    name: string;
    constructor (name: string) {
        this.name = name
    }
    run(str: string): void {
        console.log(`${this.name} is ${str}`) // xiaohei is run
    }
}
let dog = new Dog('xiaohei')
dog.run('run')

流年朝朝
128 声望12 粉丝

但行好事,莫问前程