视频位置 TypeScript快速梳理_下篇 0:34:27

interface 是⼀种定义结构的⽅式,主要作⽤是为:类、对象、函数等规定⼀种契约,这样可以确保代码的⼀致性和类型安全,但要注意 interface 只能定义格式不能包含任何实现

翻译:

  • interface 是⼀种定义结构的⽅式,主要作⽤是为:类、对象、函数等规定⼀种契约
    类中有哪些属性,哪些方法,是必须还是可选的? 都可以靠这个接口规范出来。 对象、函数也是靠这个接口规范。

抽象类能动嘴,可以指挥别人,这样…那样,你去吧。如果没人可以被指挥,抽象类也能亲自去干活。
接口类没有实际干活的能力,只能动动嘴。

用 接口 定义 类 的结构

//interface关键字规定一个接口
// PersonInterface接⼝,⽤与限制Person类的格式
interface PersonInterface {
    //规定必须有的属性
    name: string
    age: number

    //规定必须有的方法
    speak(n: number): void
}

//开始实现上面的接口:
// 定义⼀个类 Person,实现 PersonInterface 接⼝
class Person implements PersonInterface {
    //实现接⼝ 中规定的属性
    constructor(
        public name: string,
        public age: number
    ) { }

    //实现接⼝ 中规定的 speak ⽅法
    speak(n: number): void {
        for (let i = 0; i < n; i++) {
            // 打印出包含名字和年龄的问候语句
            console.log(`你好,我叫${this.name},我的年龄是${this.age}`);
        }
    }
}

//测试:
// 创建⼀个 Person 类的实例 p1,传⼊名字 'tom' 和年龄 18
const p1 = new Person('tom', 18);
p1.speak(3)

用 接口 定义 对象 结构

interface UserInterface {
    //规定必须有的属性
    name: string
    readonly gender: string // 只读属性
    //规定可有可无的属性
    age?: number // 可选属性

    //规定必须有的方法
    run: (n: number) => void
}

//此时在 对象 中, 上面定义的接口作为 类型 使用^_^
const user: UserInterface = {
    name: "张三",
    gender: '男',

    age: 18,

    run(n) {
        console.log(`奔跑了${n}⽶`)
    }
};

用 接口 定义 函数 结构

interface CountInterface {
    //规定必须有的方法,形式为:
    // 有2个参数,参数类型分别为 number number
    // 返回值类型为 number
    (a: number, b: number): number;
}

//实现
const count: CountInterface = (x, y) => {
    return x + y
}

接⼝之间的继承

interface PersonInterface {
    name: string // 姓名
    age: number // 年龄
}
//StudentInterface接口 继承 PersonInterface接口
interface StudentInterface extends PersonInterface {
    grade: string // 年级
}

//实现
const stu: StudentInterface = {
    name: "张三",
    age: 25,
    grade: '⾼三',
}

接⼝⾃动合并(可分开写)

// PersonInterface接⼝
interface PersonInterface {
    // 属性声明
    name: string
    age: number
}
// 给 PersonInterface接⼝ 添加 新属性
interface PersonInterface {
    // ⽅法声明
    speak(): void
}

// Person类实现PersonInterface
class Person implements PersonInterface {
    name: string
    age: number

    // 构造器
    constructor(name: string, age: number) {
        this.name = name
        this.age = age
    }

    // ⽅法
    speak() {
        console.log('你好!我是⽼师:', this.name)
    }
}