interface_接口

159 阅读1分钟

interface 接口 用于定义类的类型,也可以定义对象

implements(实现) 关键字

作用:要求类 要 实现 定义的类型
使用方法:类名 implements 类型

// 用 interface 定义一个 AnimalInterface 类型
interface AnimalInterface {
  name: string;
  age: number;
  sayName(): void;
}

//在 Animal 类前加上 abstract, 将 Animal 类 变为 抽象类
// 使用 implements 关键字,要求 Animal类 实现 AnimalInterface所定义的类型
abstract class Animal implements AnimalInterface {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
  // 定义抽象方法
  abstract sayName(): void;
}

// 定义Dog类,并继承 Animal 类
class Dog extends Animal {
  name: string;
  age: number;

  constructor(name: string, age: number) {
  //调用父类,并传入参数
    super(name, age);
    this.name = name;
    this.age = age;
  }

  sayName(): void {
    console.log(this.name);
  }
}

//定义 obj 对象,并要求实现 AnimalInterface 类型 
const obj: AnimalInterface = {
  name: "123",
  age: 123,
  sayName: () => {},
};

注意: 像interface 和 abstract都属于TS的实现,js是没有这些东西的

以下是打包后的代码 interface 和 abstract 都没有了。

"use strict";
class Animal {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}
class Dog extends Animal {
    constructor(name, age) {
        super(name, age);
        this.name = name;
        this.age = age;
    }
    sayName() {
        console.log(this.name);
    }
}
const obj = {
    name: "123",
    age: 123,
    sayName: () => { },
};