美文网首页TypeScript
TypeScript interface (四) 类类型 继承接

TypeScript interface (四) 类类型 继承接

作者: 邢走在云端 | 来源:发表于2019-10-23 14:13 被阅读0次

类实现接口

一个类实现一个接口,与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要将他们全部实现。

相关文章

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

    类实现接口 一个类实现一个接口,与Java里接口的基本作用一样。 一个demo? 打印结果: 继承接口 接口可以相...

  • Typescript

    安装 Typescript 接口 interface 约束类型结构、Duck Typing 类型推论、联合类型、类...

  • typescript 入门-接口

    interface 定义 可选属性 只读 函数描述 可索引 类描述 类构造器描述 混合类型 继承接口 继承类

  • 学习TypeScript 接口

    TypeScript 接口定义 interface interface_name {} 实例 联合类型和接口 接口...

  • interface 和 type aliases 区别

    TypeScript interface vs type aliases 在大多数情况下,interface和类型...

  • 4.java 接口

    java接口# 抽象类型 ,通常以interface来声明。一个类通过继承接口的方式,从而来继承接口的抽象方法。 ...

  • TypeScript 中的接口(interface)

    TypeScript 中的接口可分为: 之前的文章 TypeScript 基础类型和接口(interface)里面...

  • 面试题集六

    typescript是js类型的超集 1. interface定义: 在面向对象语言中,interface是对行为...

  • JAVA基础之接口

    关于接口(Interface)的定义,在JAVA中是一个抽象类型,一般一个类通过继承接口来继承接口中的方法。 Ja...

  • TS 中 interface,type,enum 的区别

    interface 接口 在 TypeScript 中,我们使用接口(Interfaces)来定义对象的类型。 在...

网友评论

    本文标题:TypeScript interface (四) 类类型 继承接

    本文链接:https://www.haomeiwen.com/subject/nickvctx.html