2017-02-15 3 views
0

Angular 2アプリで新しいオブジェクトを配列にプッシュしようとしていますが、私は問題に遭遇しています(Typescript型の問題かもしれませんが、特定されません)。関数のTypescriptエラー配列へのオブジェクトのプッシュ

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

私は取得していますエラー:

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

そして、ここで私は配列に新しいジップコードをプッシュする使用しています関数です。これは私のようなルックスに押してる配列は何ですかこの関数は次のとおりです。

'{postalCode:any; } 'はタイプ' {city:string;} 'のパラメータ に割り当てられません。 postalCode:文字列;座標:数値; } '。 プロパティ 'city'がタイプ '{postalCode:any; } '。

どうすればこの問題に対処できますか?ユーザーは都市や座標ではなく、郵便番号を押すでしょう。私はどのような種類のオブジェクトを配列に押し込むことができると思うだろうが、これはタイスクリプトがこれを妨げているようだ。

答えて

2

活字体は{ city: string; postalCode: string; coordinates: number; }[]として配列型を推論しているが、あなたは{postalCode:string}をプッシュしようとしている - これは誤りです。それでもやりたい場合は、locationの適切なタイプを設定する必要があります。

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

あなたは、オプションのcitycoordinatesを持つオブジェクトの配列としてlocationsを宣言することができます。

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 }, 
]; 
関連する問題