2017-02-15 63 views
0

我想将新对象推送到Angular 2应用程序中的数组,但我遇到了一个问题(我怀疑可能是一个Typescript类型的问题,尽管我是不确定)。这是我推到看起来像数组:函数中的Typescript错误将对象推入数组

locations = [ 
    { city: 'Los Angelas', postalCode: '90001', coordinates: 2321 }, 
    { city: 'New York', postalCode: '10001', coordinates: 3432 }, 
]; 

这里是我使用推新拉链码与阵列功能:

addZipcode(event) { 
    this.locations.push({ postalCode: this.newPostalCode }); 
    this.newPostalCode = ''; 
    this.addZipInput = false; 
    event.preventDefault(); 
    } 

的错误我得到re:这个函数是:

类型'{postalCode:any; }'不能分配给类型为'{city:string;'的参数 。 postalCode:string;坐标:数字; }”。 类型'{postalCode:any; }”。

我该如何处理这个问题?用户将推送邮政编码,而不是城市或坐标。我想我可以推动任何类型的对象到数组中,但似乎typecript正在阻止这种情况。

回答

2

打字稿已经推断出数组类型{ city: string; postalCode: string; coordinates: number; }[],而是你正试图推动{postalCode:string} - 这是错误。如果您仍然想这样做,那么就需要设置相应的类型location

location:any[] 
    //or 
    interface ILocation { 
    city?:string; 
    postalCode?:string; 
    coordinates?:string; 
    } 
    location:ILocation[]; 
1

你可以声明locations为对象的数组可选citycoordinates

type Loc = {city?: string; postalCode: string; coordinates?: number}; 

let locations: Loc[] = [ 
    { city: 'Los Angelas', postalCode: '90001', coordinates: 2321 }, 
    { city: 'New York', postalCode: '10001', coordinates: 3432 }, 
];