在Angular 2应用程序中实例化Typescript中的接口的正确方法是什么?

dra*_*mnl 22 typescript angular

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

据我所知,我应该在某处实现接口

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

并通过new(...)实例化它

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

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

rgv*_*sar 50

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

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

const bar: foo = { one: 5, two: "hello" };
Run Code Online (Sandbox Code Playgroud)

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

  • 另一种方法是 `const bar = { one: 5, two: "hello" } as foo`,它略有不同,因为它允许除了接口定义的属性之外的其他属性。(我只是为了完整性在这里注意到这一点 - `bar: foo` 语法是正确的,除非你需要额外的属性,因为它提供了最严格的验证。) (2认同)

Kan*_*ger 43

我用这种方式

interface IObject{
    first: number;
    second: string;
}
Run Code Online (Sandbox Code Playgroud)

然后

var myObject = {} as IObject
var myListObject = [] as Array<IObject>
Run Code Online (Sandbox Code Playgroud)

  • 这种方法破坏了类型安全的观点:https://zohaib.me/creating-object-based-on-interface-type-in​​-typescript/ (5认同)

Ste*_*aul 9

虽然接受的答案很好,但请注意这样的解决方案,因为它们允许您省略接口中定义的必需属性:

const instance1 = {} as MyInterface;
const instance2 = <MyInterface>{};
Run Code Online (Sandbox Code Playgroud)

其他一些强大而紧凑的替代方案包括:

1)实例化一个实现接口的匿名类:

new class implements MyInterface {
  one = 'Hello';
  two = 'World';
}();
Run Code Online (Sandbox Code Playgroud)

2) 或者,使用效用函数如下:

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

impl<MyInterface>({
  one: 'Hello';
  two: 'World';
})
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以执行以下操作:

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

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

然后实例化:

let newFromInterface = new MyClass();
Run Code Online (Sandbox Code Playgroud)

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

  • 那么您根本不需要定义一个接口,您只需要使用您的类即可。正确的语法是导出类MyClass实现IMyInterface (4认同)