在 TypeScript 中将接口类型添加到 class

Add types from interface to class in TypeScript

我的界面如下:

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

还有一个class:

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

  method() {}
}

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

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

的成员
interface Class extends Interface { }
class Class extends OtherClass {
  method() { }
}

new Class().c // any

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

总之,希望对您有所帮助;祝你好运!

Playground link