Issue
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?
Solution
You can do it that way. You can also just create an object that implements the interface like:
interface foo {
one: number;
two: string;
}
const bar: foo = { one: 5, two: "hello" };
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.
Answered By – rgvassar
Answer Checked By – Gilberto Lyons (BugsFixing Admin)