共计 1521 个字符,预计需要花费 4 分钟才能阅读完成。
接口
接口:行为和动作的标准,对批量办法进行束缚
属性接口
传入对象的束缚
// 惯例的属性束缚
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')
正文完
发表至: typescript
2022-02-09