代码之家  ›  专栏  ›  技术社区  ›  jeanpaul62

TypeScript:实现特定接口的任何类

  •  0
  • jeanpaul62  · 技术社区  · 7 年前

    interface CanFly {
      fly(): void;
    }
    

    我将创建两个类, Bird AirPlane

    最后,我想创建一个函数 flyIn2Seconds ,如下所示:

    function flyIn2Seconds(who: any extends CanFly) {
      setTimeout(() => who.fly(), 2000);
    }
    

    然而 any extends CanFly 不起作用( [ts] '?' expected. ). 有没有办法指定类型“any class that implements CanFly”?

    1 回复  |  直到 7 年前
        1
  •  2
  •   T.J. Crowder    7 年前

    只需指定接口:

    function flyIn2Seconds(who: CanFly) {
      setTimeout(() => who.fly(), 2000);
    }
    

    更多 the interfaces documentation

    推荐文章