Create instance using an interface

2020-05-19 05:20发布

问题:

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?

回答1:

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.



回答2:

I use this way

interface IObject{
    first: number;
    second: string;
}

then

var myObject = {} as IObject
var myListObject = [] as Array<IObject>


回答3:

You can do the following:

export interface IMyInterface {
  property1: string;
  property2: number;
  property3: boolean;
}

export class MyClass implements IMyInterface {
  property1: string = '';
  property2: number = 1;
  property3: boolean = false;
  constructor(){}
}

Then to instantiate:

let newFromInterface = new MyClass();

This is how I do it in my code at least.



回答4:

While the accepted answer is good, beware of solutions like this because they allow you to omit required properties defined in the interface:

const instance1 = {} as MyInterface;
const instance2 = <MyInterface>{};

Some other robust and compact alternatives include:

1) Instantiate an anonymous class which implements the interface:

new class implements MyInterface {
  one = 'Hello';
  two = 'World';
}();

2) Alternatively, employ a utility function as follows:

export function impl<I>(i: I) { return i; }

impl<MyInterface>({
  one: 'Hello';
  two: 'World';
})


回答5:

interface IOffice {
id: number;
employeeName: string;
phone?: number;
}
export class OfficeComponent {
  officeData: IOffice= <IOffice>{};
  dummyOfficeData: IOffice = {id: 1, employeeName: 'ragnar', phone: 123};
  noPhoneOfficeData: IOffice = {id: 2, employeeName: 'floki'};

constructor(){
  console.log(this.dummyOfficeData);
  console.log(this.dummyOfficeData);
}
}

this is better way for me. you can export interface from model file and import in any necessary components.