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关键字

  • 相关阅读:
    cookie,sessionStorage,loclaStorage,HTML5应用程序缓存
    网页设计单位 px,em,rem,vm,vh,%
    TCP协议三步挥手与四步挥手
    pycharm --批量注释和缩进
    Linux --编译kernel
    python-- pip 安装提速
    linux --tar: .BUILDINFO: time stamp 2020-08-27 17:25:55 is 68853652.868391065 s in the future .MTREE
    linux --This system is not registered to Red Hat Subscription Management
    Samba --配置Samba 服务
    linux --环境变量配置文件
  • 原文地址:https://www.cnblogs.com/codexlx/p/14442716.html
Copyright © 2011-2022 走看看