TypeScript------接口的使用
接口,一般用于声明类型,用于对复杂的数据结构进行类型描述比如对象和函数以及类
接口的基本使用
接口声明需要使用interface关键字
使用接口约束对象的类型
复制代码
1
2
3
4
5
6
7
8
9interface User{ name:string; age:number; } const user:User = { name:'张三'; age:20; };
使用接口约束函数类型
复制代码
1
2
3
4
5
6
7interface Sum{ (a:number.m:number):number; } const sun:Sum = function(a.b){ return a+b; };
使用接口约束类的成员
复制代码
1
2
3
4
5
6
7
8
9
10
11
12interface Person { name:string; addEvent():void; removeEvent():void; } class NewPerson implements Person{ name:string = 'test'; addEvent():void{} removeEvent():void{ } }
宽松的接口检查
TypeScript 接口检查时宽松的, 当变量满足了接口规范以后,几十遍了中存在接口范围以外的属性也是可以的。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15interface User{ name:string; age:number; } let user:User = { name:'张三', age:20, }; let someone = { name:'李四', age:50, sex:'男', }; user = someone;
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14interface Reportable{ summary():void; } function printSummary(item:Reportable):void{ item.summary() } const person = { name:'张三', summary(){ console.log(`hello,my name is ${this.name}`); }, }; printSummary(person);
对于宽松的接口检查政策字面量是个例外,也就是说对于字面量的接口类型检查还是严格的,不能出现接口以外的其他属性。
复制代码
1
2
3
4
5
6
7
8interface User { name:string; age:number; } const user : User = {name:'张三',age:20}; const another : User = {name:'李四',age:40,sex:'男'}; //此处会报错,因为接口内没有sex
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14interface Reportable{ summary():void; } function printSummary(item:Reportable):void{ item.summary(); } printSummary({ name:'张三', //此处会报错,name 不在类型Reportable中,对象字面量只能指定已知属性 summary(){ console.log(`hello,my name is ${this.name}`) }, });
绕过严格类型检查模式:
- 类型断言
复制代码
1
2
3
4
5
6interface User{ name:string; age:number; } const another : User = {name:'李四',age:40,sex:'男'} as User;
- 索引签名
复制代码
1
2
3
4
5
6
7interface User{ name:string; age:number; [key:string]:string | number; } const another : User = {name:'李四',age:40,sex:'男'}
接口继承
接口具有继承特性 接口与接口直接可以存在继承关系,而且一个接口可以继承多个接口
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20interface Sizes{ sizes:string[]; getSize():string[]; } interface Shape{ color:string; } //Pizza 继承了两个接口,Sizes 以及 Shape interface Pizza extends Sizes,Shap{ name:string; } let pizza:Pizza = { name:'张三', color:'skyblue', sizes:['large','small'], getSize(){ return this.sizes; }, };
在继承了接口以后可以对被继承接口中的属性进行重写,但是重写的类型一定要在原有类型的范围以内。
复制代码
1
2
3
4
5
6
7
8interface User{ name:any; age:number; } interface MyUser extends User{ name:bollean; }
接口合并
接口具有声明合并特性 多个相同名称接口会自动合并
复制代码
1
2
3
4
5
6
7
8
9interface User { height:number; width:number; } interface User{ scale:number; } let user:User = {height:5,width:6,scale:10};
最后
以上就是健康学姐最近收集整理的关于接口的基本使用的全部内容,更多相关接口内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复