ts的接口

TS中的接口

  1. 作用

接口的作用是为这些类型命名和为你的代码或者第三方代码定义契约;和前面讲的抽象类比较相似

  1. 定义接口
    通过interface关键词来定义接口

    🌰

    interface User {
    name:string
    age:number
    }
  2. 函数interface

    函数interface可规范函数的参数及返回值

    🌰

    interface Sum {
    (x:number,y:number):number
    }
    const add:Sum = () =>{
    return x + y
    }

    interface规范函数时,interface相当于type 当一个函数类型是接口时,要求 :

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

    • 继承的好处是复用代码,并且层级关系清晰。但JavaScript中继承是单继承,一个类只能有一个父类
    • 而在TypeScript中interface会显得更加灵活,因为interface可以多实现
    • 通过implements关键字可以让一个类实现一个接口,要求必须实现接口定义的方法

    🌰

    interface ClockInterface {
    currentTime: Date;
    }
    class Clock implements ClockInterface {
    currentTime: Date;
    constructor(h: number, m: number) { }
    }

    接口描述了类的公共部分,而不是公共和私有两部分。 它不会帮你检查类是否具有某些私有成员。

  4. 构造函数interface

    • 构造函数interface比较特殊,是通过赋值的形式来实现,并且得跟普通interface区分开,普通interface还是使用implements
    • 另外在接口中使用new指代构造器
    • 跟类一样,interface也能继承另外一个interface

    🌰

    interface Person {
    name: string;
    age?: number;
    [propName: string]: any;
    say(): string;
    teach(): string;
    }
    interface Teacher extends Person {
    teach(): string
    }
    let viking: Teacher = {
    name: 'lily',
    say(){
    return 'hello'
    },
    teach() {
    return 'tech'
    }
    }
posted @   前端加油站  阅读(143)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示