Export class as interface in Angular2

前端 未结 1 731
臣服心动
臣服心动 2020-12-07 04:49

Is there a way to export a class as interface and then import that interface in another module in Angular 2? I need to be able to inject the class in a constructor in some c

相关标签:
1条回答
  • 2020-12-07 05:41

    In order to be used as both an interface and provider token, it may be abstract class. This is how it is done in Angular code base itself.

    If concrete class has something to inherit from abstract class, the latter can be extendable:

    export abstract class Foo {
      abstract bar();
    
      baz() { ... }
    }
    
    export class ConcreteFoo extends Foo {
      bar() { ... }
    }
    
    ...
    provider: [{ provide: Foo, useClass: ConcreteFoo }]
    ...
    

    Otherwise it's safer to make abstract class non-extendable and non-instantiatable:

    export abstract class Foo {
      private constructor() {
        throw new Error('should not be instantiated directly');
      }
    
      abstract bar();
    }
    
    export class ConcreteFoo implements Foo {
      bar() { ... }
    }
    

    It should be noticed that any class can be used as an interface in TypeScript. So if there's no real need to differentiate between interface and implementation, it may be just one concrete class:

    export class Foo {
      bar() { ... }
    
      baz() { ... }
    }
    
    ...
    provider: [Foo]
    ...
    

    Which may be used later as an interface if necessary:

    export class SomeFoo implements Foo { ... }
    
    ...
    provider: [{ provide: Foo, useClass: SomeFoo }]
    ...
    
    0 讨论(0)
提交回复
热议问题