简体   繁体   English

将数组分配给对象

[英]Assign array to object

I'm migrating my app from AngularJs to Angular 4.我正在将我的应用程序从 AngularJs 迁移到 Angular 4。

I have used following type of statements very often in my code by they all are failing in Angular 4 (TypeScript):我在我的代码中经常使用以下类型的语句,因为它们在 Angular 4 (TypeScript) 中都失败了:

Edit: Following lines were used in AngularJS编辑:在 AngularJS 中使用了以下几行

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

I tried this in my component class in Angular4 :在 Angular4 的组件类中尝试了这个:

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

It gives error: Property AccomodationAddresses does not exist :(它给出了错误:属性 AccomodationAddresses 不存在 :(

Typescript uses inference from assignment to determine the type of a variable. Typescript 使用赋值推理来确定变量的类型。

You can either use any to get out of the type system altogether (not a great option) :您可以使用 any 完全退出类型系统(不是一个很好的选择):

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:如果可行,您也可以一次全部初始化并让 TS 推断出正确的类型:

let accomodation = { AccomodationAddresses: [] }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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