zoukankan      html  css  js  c++  java
  • TS之类与接口

     1.类与接口

    interface Raddio {
      switchRadio(trigger: boolean): void
    }
    
    class Car implements Raddio {
      switchRadio(trigger: boolean) {}
    }
    
    class CellPhone implements Raddio {
      // switchRadio(trigger: boolean) {}
    }

    JS中的类只能通过继承自另外一个类,有时候不同的类之间需要实现一个共同的方法,使用子类继承父类的方法很难完成。此时可以把这写共同的特性提取成接口,使用implements关键字来实现,这样就大大提高了面向对象的灵活性。

    示例:

      两个类,但是都要实现一个相同的方法:

    class Car {
      switchRadio(trigger: boolean) {}
    }
    
    class CellPhone {
      switchRadio(trigger: boolean) {}
    }

    switchRadio方法就是这两个类都要实现的相同的方法。此时如果使用父类的形式来实现。那么需要有个父类让这两个类来继承自这个父类。此时可以使用TS的接口来实现这个功能:
    先定义一个接口,然后使用implements关键字让这个类来实现它:

    interface Raddio {
      switchRadio(trigger: boolean): void
    }
    
    class Car implements Raddio {
      switchRadio(trigger: boolean) {}
    }
    
    class CellPhone implements Raddio {}

    此时如果第二个类没有实现这个方法的话就会出现错误提示:Class 'CellPhone' incorrectly implements interface 'Raddio'.Property 'switchRadio' is missing in type 'CellPhone' but required in type 'Raddio'

     2.接口之间的继承

    注意这里接口的继承不是class的继承。

     例如一个类需要实现两个接口里面的方法,可以使用同时实现两个接口的方法实现:

    interface Radio {
      switchRadio(trigger: boolean): void
    }
    
    interface Battery {
      checkBatteryStatus(): void
    }
    
    class CellPhone implements Radio, Battery {
      switchRadio(trigger: boolean) {}
      checkBatteryStatus() {}
    }

    这样 CellPhone 这个类就实现了两个接口的两个方法,还有一种方法就是使用另一个接口继承自Radio接口,CellPhone类就可以只实现一个接口即可:

    interface Radio {
      switchRadio(trigger: boolean): void
    }
    
    interface RadioWithBattery extends Radio {
      checkBatteryStatus(): void
    }
    
    class CellPhone implements RadioWithBattery {
      switchRadio(trigger: boolean) {}
      checkBatteryStatus() {}
    }

    接口继承 使用方法同类的继承,都是使用extends关键字

  • 相关阅读:
    ps4 如何导出切片 单个图片
    测试webservice的时候,如果出现这个错误:"The test form is only available for requests from the local machine"
    js jquery 按钮点击后 60秒之后才能点击 60秒倒计时
    有空研究一下 superwebsocket (底层是 supersocket) 用来实现 web聊天什么的
    Vue学习笔记一:初识Vue
    被爬虫了,嘻嘻嘻
    Mybatis-generator自动生成器
    SpringCloud笔记五:Feign
    SpringCloud笔记四:Ribbon
    SpringCloud笔记三:Eureka服务注册与发现
  • 原文地址:https://www.cnblogs.com/codexlx/p/14442716.html
Copyright © 2011-2022 走看看