【问题标题】:Create instance using an interface使用接口创建实例
【发布时间】:2016-08-13 10:34:21
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

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

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

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

    【讨论】:

    • 另一种方式是: interface foo { one?: number;二?:字符串; } 常量栏: foo = {}
    • 另一种方式是const bar = { one: 5, two: "hello" } as foo,它略有不同,因为它允许接口定义的属性之外的其他属性。 (为了完整起见,我只是在此注明——bar: foo 语法是正确的,除非您需要其他属性,因为它提供了最严格的验证。)
    【解决方案2】:

    我用这种方式

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

    然后

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

    【讨论】:

    【解决方案3】:

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

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

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

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

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

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

    export function impl<I>(i: I) { return i; }
    
    impl<MyInterface>({
      one: 'Hello';
      two: 'World';
    })
    

    【讨论】:

      【解决方案4】:

      您可以执行以下操作:

      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();
      

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

      【讨论】:

      • 那么你根本不需要定义接口,你只是在使用你的类。正确的语法是导出类 MyClass 实现 IMyInterface
      【解决方案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);
      }
      }
      

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

      【讨论】:

        猜你喜欢
        • 2011-10-30
        • 2016-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多