typescriptclassinterface

Add types from interface to class in TypeScript


I have an interface like:

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

And a class:

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

  method() {}
}

Is there a way to reduce duplication of type definitions?


Solution

  • You could use declaration merging to inform the compiler that the interface for instances of Class includes members from Interface:

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

    Note that this circumvents strict property initialization checking, so the compiler will not be able to catch if you fail to initialize those properties. So be careful if you do this... either initialize the properties or make sure that their types can be undefined.

    Playground link