ts接口类型有哪些
dearweb 发布:2021-07-25 20:47:11阅读:在程序设计里面,接口起到了一种限制和规范的作用,接口定义了某一批类所需要遵守的规范,接口不关心这些类的内部状态数据,也不关心这些类里的方法的实现细节,它只规定这批类必须提供某些方法,提供这些方法的类就可以满足实际需求。typescript中的接口类似于java,同时还增加了更灵活的接口类型,包括属性、函数、可索引和类等。
1.属性类接口
interface FullName{ firstName:string; secondName:string; } function printName(name:FullName){ console.log(name.firstName+'---'+name.secondName) } // printName({firstName:'小红',secondName:'小明'}) let objName = { firstName:'小红', secondName:'小明', cityName:'北京' } printName(objName) 可选属性 interface FullName{ firstName:string; secondName?:string; //: 前面加问号 表示该参数可传可不传 } function printName(name:FullName){ console.log(name.firstName+'---'+name.secondName) } // printName({firstName:'小红',secondName:'小明'}) let objName = { firstName:'小红', secondName:'小明', cityName:'北京' } printName(objName)
2.函数类接口(加密的函数类型接口)
// 加密的函数类型接口 interface encrypt{ (key:string,value:string):string; } let md5:encrypt=function(key:string,value:string):string{ // 模拟操作 return key+value } console.log(md5('name','小红')) 可索引接口,数组、对象的约束(不常用) 定义数组的方式 let arr:number[] = [12345,888] let arrArr:Array<string>=['wuhan',"北京"]
3.可索引接口(接口数组、对象的约束(不常用))
interface UserArr{ [index:number]:string } let UserArr:UserArr = ['wuhan','beijing'] console.log(UserArr[0]) // 可索引接口,对对象约束 interface UserObj{ [index:string]:string } let UserObj:UserObj = {'name':'李四'} console.log(UserObj.name) // 李四
4.类类型接口(在面向对象的对类的约束 和 抽象类有点相似)
interface Animal{ name:string; eat(str:string):void; } class Dog implements Animal{ name:string; constructor(name:string) { this.name = name } eat(){ console.log(this.name+'武汉') } } let D = new Dog('city25') console.log(D.eat()) // {name: "city25"} class Cat implements Animal{ name:string; constructor(name:string) { this.name = name } eat(food:string){ console.log(this.name+food) } } let C = new Cat('小猫') console.log(C.eat('老鼠')) // {name: "city25"}
5.接口扩展(接口也可以继承)
interface Animal{ eat():void; } interface Person extends Animal{ work():void } class Web implements Person { name:string constructor(name:string) { this.name =name } eat(){ console.log('喝茶') } work(){ console.log(this.name+'写代码') } } let W = new Web('小红') W.work() // 小红写代码 // 接口扩展:接口可以继承接口 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 + code + '凌晨4点还在写代码') } } class Web extends Programmer implements Person { constructor(name:string) { super(name) } eat(){ console.log('喝茶') } work(){ console.log(this.name+'写代码') } } let W = new Web('小红') W.work() // 小红写代码 W.coding('5月22日') // 小红5月22日凌晨4点还在写代码
小礼物走一波,支持作者
赏还没有人赞赏,支持一波吧