【问题标题】:Add types from interface to class in TypeScript在 TypeScript 中将类型从接口添加到类
【发布时间】:2020-08-13 00:43:23
【问题描述】:

我有一个类似的界面:

interface Interface {
  a: any
  b: any
  c: any
  d: any
  e: any
  f: any
  etc: any
}

还有一个班级:

class Class extends OtherClass implements Interface {
  a: any
  b: any
  c: any
  d: any
  e: any
  f: any
  etc: any

  method() {}
}

有没有办法减少类型定义的重复?

【问题讨论】:

    标签: typescript class interface


    【解决方案1】:

    您可以使用declaration merging 通知编译器Class 实例的接口包含来自Interface 的成员:

    interface Class extends Interface { }
    class Class extends OtherClass {
      method() { }
    }
    
    new Class().c // any
    

    请注意,这会绕过strict property initialization checking,因此如果您未能初始化这些属性,编译器将无法捕获。所以如果你这样做要小心......要么初始化属性,要么确保它们的类型可以是undefined

    无论如何,希望对您有所帮助;祝你好运!

    Playground link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-06
      • 2017-05-28
      • 1970-01-01
      • 2018-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      相关资源
      最近更新 更多