首页 > 解决方案 > 如何定义接口的对象数组?我的数据:数组=[]; 我得到属性 'xxxxxx' 在类型 'myInterface[]' 上不存在

问题描述

我正在尝试为对象数组定义一个接口,我希望组件中的初始值是一个空数组

我在文件中有一个接口:

export interface myInterface{
 "picture": string,
 "lastUpdated": Date
}

在我的组件中,我导入了这个接口:

import {myInterface} from "./interfaces/myInterface"
.
.
myData:Array<myInterface>=[];  //default [] initial value
.
.
//I get the data by a rest api
then((data) => {
  this.myData=data;
  this.myData.lastUpdated= new Date();  //Property 'lastUpdated' does not exist on type 'myInterface[]'
})

我收到此错误:

this.myData.lastUpdated= new Date();  //Property 'lastUpdated' does not exist on type 

如何解决?

标签: angulartypescript

解决方案


我不确定您是想要它们的第一个值lastUpdated还是全部。 myData是一个对象数组,你应该遍历它以处理它的所有值

myData: MyInterface[] = []; // EMPTY array of type MyInterface
myLastUpdatedArray: any = []; // EMPTY array of type any
...
then((data) => {
  this.myData = data;

  const aVariable = this.myData[0].lastUpdate; // aVariable will hold your .lastUpdated value
 
  // if you want all of them
  myData.forEach((data) => this.myLastUpdatedArray.push(data.lastUpdated));
})

推荐阅读