我将我的应用从AngularJs迁移到Angular 4。
我在代码中经常使用以下类型的语句,因为它们在Angular 4(TypeScript)中都失败了:
编辑:在AngularJS中使用了以下行
var accomodation = {};
accomodation.AccomodationAddresses = [];
我在Angular4
中的类中尝试了这个this.accomodation = {};
this.accomodation.AccomodationAddresses = [];
它给出错误:Property AccomodationAddresses不存在:(
答案 0 :(得分:3)
Typescript使用赋值的推理来确定变量的类型。
你可以使用any来完全退出类型系统(不是一个很好的选择):
let accommodation : any = {};
accomodation.AccomodationAddresses = [];
或者您可以明确指出变量的类型:
let accommodation : { AccomodationAddresses?: any[] } = {}; // used any but you can use a more explicit type
accomodation.AccomodationAddresses = [];
或使用命名界面:
interface Accomodation { AccomodationAddresses?: any[] } // used any but you can use a more explicit type
let accommodation : Accomodation = {}; accomodation.AccomodationAddresses = [];
如果可行,您也可以一次初始化它并让TS推断出正确的类型:
let accomodation = { AccomodationAddresses: [] }