簡體   English   中英

如何在打字稿角度定義復雜屬性的接口

[英]How to define interface for complex properties in typescript angular

我的 Angular 應用程序中有員工對象數組。 我需要為它輸入類型而不是any ,所以我定義了interface 但我得到如下錯誤。

src/app/newComp/employee/employee.component.ts(11,3) 中的錯誤:錯誤 TS2322:類型 '{empID:string; 名稱:字符串; 性別:字符串; 工資:數字; DOB:字符串; }[]' 不可分配給類型 'Employees'。 類型“{ empID: string;”中缺少屬性“empID” 名稱:字符串; 性別:字符串; 工資:數字; DOB:字符串; }[]'。 src/app/newComp/employee/employee.component.ts(20,7): error TS2322: Type '{ empID: string; 名稱:字符串; 性別:字符串; 工資:數字; DOB:字符串; }[]' 不可分配給類型 'Employees'。 類型“{ empID: string;”中缺少屬性“empID” 名稱:字符串; 性別:字符串; 工資:數字; DOB:字符串; }[]'。

如何解決這個問題? 這是我的整個代碼。

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>{}

更改行號 2。

員工:員工; 給員工:員工[];

請參閱此示例代碼

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') }
];

  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM