简体   繁体   中英

Assign array to object

I'm migrating my app from AngularJs to Angular 4.

I have used following type of statements very often in my code by they all are failing in Angular 4 (TypeScript):

Edit: Following lines were used in AngularJS

var accomodation = {};
accomodation.AccomodationAddresses = [];

I tried this in my component class in Angular4 :

this.accomodation = {};
this.accomodation.AccomodationAddresses = [];

It gives error: Property AccomodationAddresses does not exist :(

Typescript uses inference from assignment to determine the type of a variable.

You can either use any to get out of the type system altogether (not a great option) :

let accommodation : any = {};
accomodation.AccomodationAddresses = [];

Or you can be explicit about the type of the variable:

let accommodation : { AccomodationAddresses?: any[] } = {}; // used any but you can use a more explicit type
accomodation.AccomodationAddresses = [];

Or use a named interface:

interface Accomodation { AccomodationAddresses?: any[] } // used any but you can use a more explicit type
let accommodation : Accomodation  = {};     accomodation.AccomodationAddresses = [];

If it is feasible you can also initialize it all at once and have TS infer the correct type:

let accomodation = { AccomodationAddresses: [] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM