美文网首页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 (四) 类类型 继承接

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