自动将JSON对象映射到TypeScript对象(Angular 2)
问题描述:
我是Typescript和JavaScript的新手。 我的问题是: 如何从这个自动将JSON对象映射到TypeScript对象(Angular 2)
```
{
"release": {
"ref": {},
"commits": {}
},
"debug": {
"ref": {},
"commits": {}
},
"feature": {
"ref": {},
"commits": {}
},
"hotfix": {
"ref": {},
"commits": {}
}
}
```
地图它与打字稿使用接口
export interface IRepo { branches: IBranch; // how to make branches a of type string: IBranch dictionary? }
会有未知像调试,发布等属性的数量, 我想保留它们在IRepo实例字典
我使用这个来获取数据:
```
getRepo() : Observable<IRepo> {
if (!this.repo) {
return this.http.get(this._baseUrl + 'repo.json')
.map((res: Response) => {
this.repo = res.json();
return this.repo;
})
.catch(this.handleError);
} else {
return this.createObservable(this.repo);
}
}
```
答
你有一张地图,从一些知去(具有ref
commits
)。只需使用字符串索引器:
interface BranchByName {
[branchName: string]: {
ref: any;
commits: any;
}
}
属性有哪些类型?如果你不需要强类型,你可以用for-in迭代对象的属性。如果你需要在编译时强制输入它们,你能指定它们的类型(如果有任何共同点) –