【问题标题】:How to define interface for complex properties in typescript angular如何在打字稿角度定义复杂属性的接口
【发布时间】:2019-03-28 17:00:46
【问题描述】:

我的 Angular 应用中有 employees 对象数组。我需要为它输入 type 而不是 any,所以我定义了 interface。但我得到如下错误。

src/app/newComp/employee/employee.component.ts(11,3) 中的错误:错误 TS2322:类型 '{ empID: string;名称:字符串;性别:字符串;工资:数字;出生日期:字符串; }[]' 不可分配给类型“员工”。 '{ empID: string; 类型中缺少属性 'empID'名称:字符串;性别:字符串;工资:数字;出生日期:字符串; }[]'。 src/app/newComp/employee/employee.component.ts(20,7): 错误 TS2322: Type '{ empID: string;名称:字符串;性别:字符串;工资:数字;出生日期:字符串; }[]' 不可分配给类型“员工”。 '{ empID: string; 类型中缺少属性 'empID'名称:字符串;性别:字符串;工资:数字;出生日期:字符串; }[]'。

如何解决这个问题?这是我的全部代码。

export class EmployeeComponent {
employees: Employees;
constructor() {
this.employees = [
{ empID: 'empid101', name: 'Jhon', gender: 'male', salary: 1200, DOB: '12/24/2016' },
{ empID: 'empid102', name: 'Nancy', gender: 'female', salary: 2445.23, DOB: '4/2/2016' },
{ empID: 'empid103', name: 'Julie', gender: 'female', salary: 5000.23, DOB: '4/14/2016' },
{ empID: 'empid104', name: 'Brito', gender: 'male', salary: 4352, DOB: '5/12/2016' }
];
}
/* tslint:disable */
refreshTheData(): void {
  this.employees = [
    { empID: 'empid101', name: 'Jhon', gender: 'male', salary: 1200, DOB: '12/24/2016' },
    { empID: 'empid102', name: 'Nancy', gender: 'female', salary: 2445.23, DOB: '4/2/2016' },
    { empID: 'empid103', name: 'Julie', gender: 'female', salary: 5000.23, DOB: '4/14/2016' },
    { empID: 'empid104', name: 'Brito', gender: 'male', salary: 4352, DOB: '5/12/2016' },
    { empID: 'empid105', name: 'Clark', gender: 'male', salary: 7543, DOB: '2/15/1990' }   ];    }



 interface Employees{
  empID: string,
  name: string,
  gender: string,
  salary: number,
  DOB: Date
}
interface Employees extends Array<Employees>{}

【问题讨论】:

    标签: angular typescript interface


    【解决方案1】:

    更改行号 2。

    员工:员工;给员工:员工[];

    See this for sample code

    import { Component } from '@angular/core';
    
     interface Employees {
      empID: string;
      name: string;
      gender: string;
      salary: number;
      DOB: Date
    }
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
    name = 'Angular';
    employees: Employees[];
    constructor() {
    
    this.employees = [
    { empID: 'empid101', name: 'Jhon', gender: 'male', salary: 1200, DOB: new Date('12/24/2016') }
    ];
    
      }
    }
    

    【讨论】:

    • 为避免进一步混淆,您还应该考虑将接口Employees 重命名为Employee,因为该接口只描述了一个员工。
    • 对我来说最清晰的方法是使用Employee 接口而不是type Employees = Employee[] 之类的类型
    • 重命名为 Employee 也可能被视为一种不好的做法,例如在 .NET 中,modelName 的最佳做法是Employees
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 2017-06-29
    • 2019-04-09
    • 2021-08-08
    • 2019-05-28
    相关资源
    最近更新 更多