TypeScript interface (四) 类类型 继承接口

类实现接口

一个类实现一个接口,与Java里接口的基本作用一样。

一个demo🌰

// 动物的接口 
interface Animal {
  type: string;
  sound: string;
  voice():void;
}

// Dog类实现接口
class Dog implements Animal {
  type:string;
  sound: string;
    
  voice():void {
    console.log(`${this.sound}, 我是${this.type}`)
  }

  constructor(sound: string,type: string) { 
    this.sound = sound
    this.type = type
  }
}

// Cat类实现接口
class Cat implements Animal {
  type: string;
  sound: string;
    
  voice(): void {
    console.log(`${this.sound}, 我是${this.type}`)
  }

  constructor(sound:string, type: string) {
    this.sound = sound;
    this.type = type;
  }
}

new Cat("喵喵~","哺乳类").voice();
new Dog("汪汪~","哺乳类").voice();

打印结果:

喵喵~, 我是哺乳类
汪汪~, 我是哺乳类

继承接口

接口可以相互继承

一个demo🌰

// 生物体的接口
interface Creature  {
  name: string;
}

// 动物接口  继承生物接口
interface Animal extends Creature {
  // 自己拥有的属性 action
  action(): void;
}

class Dog implements Animal {
  name: string; // name是 Animal继承自 Creature的,不实现会报错
  action(): void {
    console.log(`我是${this.name}`)
  }

  constructor (name: string) {
    this.name = name;
  }
}

new Dog("狗狗").action()  // 我是狗狗

类必须实现它的接口的所有属性,包括它继承自父类的属性

💦另外:接口可以多继承:一个接口可以继承多个接口

一个demo🌰

// 生物体的接口
interface Creature {
  name: string;
}

// 动物接口  
interface Animal {
  // 自己拥有的属性 action
  action(): void;
}

// 狗Dog接口继承 生物Creature 和 Animal 多继承
interface Dog extends Creature, Animal{
  color: string;
}


class Golden implements Dog {
  name: string;
  color: string;
  action():void {
    console.log(`我是${this.name},我的颜色是${this.color}`)
  }

  constructor(name: string, color:string) {
    this.name = name;
    this.color = color;
  }
}

new Golden("金毛","金黄色").action() // 我是金毛,我的颜色是金黄色

Golden 实现了 Dog接口,Dog接口多继承了Creature 和 Animal两个接口,拥有了他们的属性,所以Golden要将他们全部实现。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容