interface Place{
title: string,
location: string
}
interface CommunityObj{
currentLocatin: string,
hasFound: number,
list?: Place[]
}
let place:CommunityObj;
place.currentLocatin= "wdf";
place.hasFound = 1;
place.list = [{title:'sdf', location:"sdf"}];
console.log(place);

interface Place{
title: string,
location: string
}
class CommunityClass{
currentLocation:string;
hasFound:number;
list?: Place[]
}
let place = new CommunityClass();
place.currentLocation= "wdf";
place.hasFound = 1;
place.list.push({title:'sdf', location:"sdf"});
console.log(place);

还是有错误
TypeScript 的所有类型申明在转译成 JavaScript 的时候都会被去掉。所以
let place:CommunityObj;
实际上就是let place;
,这里并没有赋值,所以是undefined
。OK,你发现了这个问题,所以用
let place = new CommunityClass();
来解决了,这没问题。然后后面用到
place.list
也是undefined
,原因类似。因为这里只是申明了
CommunityClass
类中有一个类型为Place[] | undefined
的list
,并没有赋值。你可以在使用之前给它赋个值,比如
更好的做法是在定义类属性的时候给它赋初值