Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create instance using an interface

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?

like image 259
dragonmnl Avatar asked Apr 20 '16 15:04

dragonmnl


People also ask

How do I create an instance of an interface?

Interface can not be directly instantiated. We can create an instance of a class that implements the interface, then assign that instance to a variable of the interface type. IControl c= new DemoClass(); 0.

Can we create an instance of an interface?

No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete. Still if you try to instantiate an interface, a compile time error will be generated saying “MyInterface is abstract; cannot be instantiated”.

Can I create an instance of interface class?

You cannot create an instance of an interface , because an interface is basically an abstract class without the restriction against multiple inheritance. And an abstract class is missing parts of its implementation, or is explicitly marked as abstract to prohibit instantiation.

Can we create instance of interface C#?

Actually you cannot create an instance of an interface. You create an instance of some class, implementing the interface. Actually there can be dozens of classes, implementing one interface.


1 Answers

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.

like image 126
rgvassar Avatar answered Sep 21 '22 17:09

rgvassar