【问题标题】:How to declare a typescript property that implements multiple interfaces如何声明实现多个接口的打字稿属性
【发布时间】:2016-06-07 01:00:53
【问题描述】:

假设我有 2 个接口:

interface Interface1{}
interface Interface2{}

有没有办法将一个属性声明为实现两个接口?比如:

class MyClass{
  public p: Interface1, Interface2
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    有没有办法将一个属性声明为实现两个接口?比如:

    是的。一个intersection type:

    interface Interface1{}
    interface Interface2{}
    class MyClass{
      public p: Interface1 & Interface2
    }
    

    更多

    这里有介绍https://basarat.gitbooks.io/typescript/content/docs/types/type-system.html

    【讨论】:

      【解决方案2】:
      interface Interface1 { }
      interface Interface2 { }
      interface ICombination extends Interface1, Interface2 { };
      class MyClass {
          public p: ICombination
      }
      

      【讨论】:

      • 这个工作正常,但缺点是随着接口数量的增加,组合的数量增长非常快。根据用例,这可能不是问题,但需要考虑。
      猜你喜欢
      • 2019-03-26
      • 2019-05-28
      • 2017-06-29
      • 2020-09-06
      • 2021-02-06
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      • 2021-01-20
      相关资源
      最近更新 更多