In my Angular 2 TypeScript application, I defined an interface rather than a class to allow optional parameters.
As far as I know, I should somewhere implement the interface by:
export class myClass implements myInterface { ... }
and then instantiate it via new(...)
.
I wondered whether this is the right way to do it (in Angular 2) or there is a simpler / better way?
Also, where should I put the implementation, in the component (.ts) where I use it, where the interface is or where?
While the accepted answer is good, beware of solutions like this because they allow you to omit required properties defined in the interface:
Some other robust and compact alternatives include:
1) Instantiate an anonymous class which implements the interface:
2) Alternatively, employ a utility function as follows:
You can do it that way. You can also just create an object that implements the interface like:
If you want to use a class, you can put it where you want. If it's tightly coupled with the component, you can put it there. Generally though, I want classes to be loosely coupled, so I put them in their own file.
I use this way
then
this is better way for me. you can export interface from model file and import in any necessary components.
You can do the following:
Then to instantiate:
This is how I do it in my code at least.