Search code examples
angulartypescriptserviceinterface

Angular - Should I remove unused interface?


In my project I have created an interface like so:

interface IExport {
    export(): Observable<ArrayBuffer>;
}

I have several services that implement this interface for example:

@Injectable({ providedIn: 'root' })
export class BookService implements IExport {

    export() { // }
}

@Injectable({ providedIn: 'root' })
export class CompanyService implements IExport {

    export() { // }
}

@Injectable({ providedIn: 'root' })
export class DocumentService implements IExport {

    export() { // }
}

Is it a good practice or even needed to create this interface IExport, given that I dont have any reference to it from a component. The way I'm using it is like so:

@Component({
    selector: 'app-book-component',
    templateUrl: './book.component.html'
})
export class BookComponent {
   constructor(private service: BookService)

   exportBook(){
     service.export().subscribe();
   }
}

So as you can see I have not defined the service in the component as a IExportService. Is it a good idea to keep it, remove it, or add the interface when needed ?


Solution

  • The point of an interface which is implemented via the implements keyword is that it serves as a contract under which the implementer (in this case your services) must comply.

    In your case the implemented interface serves/served two purposes:

    1. It provided an error when you first created your service if the export method was not included in the service file
    2. It will provide the same error if you (or another developer!) attempts to remove export in future
    @Injectable({ providedIn: 'root' })
    export class BookService implements IExport {
      // Property 'export' is missing in type 'BookService' but required in type 
    'IExport'.(2420)
    }
    

    Whether you should use implements is entirely subjective. The same could be said for creating any interfaces/types in totality. You either believe in the compile-time benefits they provide or consider it redundant/wasted effort.

    I personally prefer to "describe" my code via TypeScript as much as possible with explicit typing and tools like implements so that other developers (and the compiler) know the intended use of my code. Other developers prefer to be more lean with their TypeScript and leverage type inference to keep their code less verbose. Both have pros and cons but ultimately it is upto yourself/your team to agree on which is most practical for your application.

    The most important thing is to be consistent throughout your codebase!