TS中接口的使用
2020-11-05 本文已影响0人
深度剖析JavaScript
接口是一种规范,跟抽象类有点类似
通过 interface
关键字定义接口,格式如下:
interface xxx{
属性: 类型 ;
...
(函数参数) : 返回值类型
...
}
interface
一般用于规范三个东西:
- 函数
- 类
- 构造器
一、函数interface
函数interface
可规范函数的参数及返回值
interface xxx{
(参数,...):返回值类型
}
例如
interface SearchFn {
(key: string, page?: number): number[]
}
const search: SearchFn = function (key: string, page: number) {
return [1, 2, 3]
}
我们可以看到,interface
规范函数时,interface
相当于type
当一个函数类型是接口时,要求:
- 参数名可不一致,但参数的值类型必须与接口定义的对应,且参数可以少不可多;
- 返回值必须有,且与接口定义的一致;
一、类interface
我们知道,继承的好处是复用代码,并且层级关系清晰。但JavaScript
中继承是单继承,一个类只能有一个父类。而在TypeScript
中interface
会显得更加灵活,因为interface
可以多实现
例如:
interface serialization {
toJSON(): object;
formJSON(json: object): void;
}
class Box implements serialization {
width: number;
height: number;
constructor(width:number,height:number){
this.width = width;
this.height = height;
}
toJSON(): object {
return { width: this.width, height: this.height }
}
formJSON(json: object): void {
if (isSize(json)) {
this.width = json.width;
this.height = json.height;
}
}
}
function isSize(json: any): json is { width: number, height: number } {
if (typeof json != 'object') {
console.log('必须是object类型');
} else {
if (typeof json.width != 'number' || typeof json.height != 'number') {
console.log('width 和 height 必须是number类型!!')
}
}
return true;
}
let box = new Box(50,50)
如上,通过implements
关键字可以让一个类实现一个接口,要求必须实现时间接口定义的方法,否则会出错
三、构造函数interface
构造函数interface
比较特殊,是通过赋值的形式来实现,并且得跟普通interface
区分开,普通interface
还是使用implements
。另外在接口中使用new
指代构造器
interface BoxConstructorInterface{
new (a:string)
}
interface BoxInterface{
show(a:number):void;
}
const Box:BoxConstructorInterface = class implements BoxInterface {
private a:string;
constructor(a:string){
this.a = a;
}
show(a:number){
console.log(this.a)
}
}
另外,跟类一样,interface
也能继承另外一个interface
例如:
interface A { }
interface B extends A { }
class C implements B { }
所以,我们知道了,接口本身只是一种规范,里头定义了一些必须有的属性或者方法,接口可以用于规范function
、class
或者constructor
,只是规则有点区别
以上就是TS中interface
的基本使用!