使用接口创建实例

问题描述 投票:16回答:4

在我的Angular 2 TypeScript应用程序中,我定义了一个接口而不是一个类来允许可选参数。

据我所知,我应该通过以下方式实现接口:

导出类myClass实现myInterface {...}

然后通过new(...)实例化它。

我想知道这是否是正确的方法(在Angular 2中)或者是否有更简单/更好的方法?

另外,我应该把实现放在我使用它的组件(.ts)中,接口在哪里或哪里?

typescript angular
4个回答
44
投票

你可以这样做。您还可以创建一个实现接口的对象,如:

interface foo {
    one: number;
    two: string;
}

const bar: foo = { one: 5, two: "hello" };

如果你想使用一个类,你可以把它放在你想要的地方。如果它与组件紧密耦合,您可以将其放在那里。一般来说,我希望类松散耦合,所以我把它们放在自己的文件中。


38
投票

我用这种方式

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

然后

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

2
投票

您可以执行以下操作:

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

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

然后实例化:

let newFromInterface = new MyClass();

这就是我至少在代码中这样做的方式。


0
投票
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);
}
}

这对我来说是更好的方式。您可以从模型文件导出接口并导入任何必要的组件。

© www.soinside.com 2019 - 2024. All rights reserved.