使用界面创建实例 [英] Create instance using an interface
问题描述
在Angular 2 TypeScript应用程序中,我定义了一个接口而不是一个类来允许可选参数.
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:
导出类myClass实现myInterface {...}
export class myClass implements myInterface { ... }
,然后通过new(...)
实例化它.
我想知道这是正确的方法(在Angular 2中)还是有更简单/更好的方法?
I wondered whether this is the right way to do it (in Angular 2) or there is a simpler / better way?
此外,我应该在哪里将实现放在中,放在我使用它的组件(.ts)中,接口在哪里或在哪里?
Also, where should I put the implementation, in the component (.ts) where I use it, where the interface is or where?
推荐答案
您可以这样做.您还可以创建一个实现如下接口的对象:
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.
这篇关于使用界面创建实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!