TS中的接口,你是否陌生?

1,480 阅读2分钟

前言

今天我们来继续学习TS

这节我们来看TS中的接口,不知道你是否陌生?

我们先来看他的作用吧

作用

官方的说法是

TS,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约

看完可能你还是不太理解!其实简单来说,跟抽象类有点类似,不知道你是否了解抽象类。如果你不了解也没关系,你就把接口当成一种规范即可

下面看如何定义一个接口

定义接口

通过 interface关键字定义接口,格式如下:

interface xxx{
  属性: 类型 ;
  ...
  (函数参数) : 返回值类型
  ...
}

interface一般用于规范三个东西:

  1. 函数
  2. 构造器

函数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 当一个函数类型是接口时,要求:

  1. 参数名可不一致,但参数的值类型必须与接口定义的对应,且参数可以少不可多;
  2. 返回值必须有,且与接口定义的一致;

类interface

我们知道,继承的好处是复用代码,并且层级关系清晰。但JavaScript中继承是单继承,一个类只能有一个父类。而在TypeScriptinterface会显得更加灵活,因为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 { }

所以,我们知道了,接口本身只是一种规范,里头定义了一些必须有的属性或者方法,接口可以用于规范functionclass或者constructor,只是规则有点区别

END

以上就是本文的相关内容,如有问题欢迎指正~