2016-07-05 159 views
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); 
    } 
} 

```

+0

屬性有哪些類型?如果你不需要強類型,你可以用for-in迭代對象的屬性。如果你需要在編譯時強制輸入它們,你能指定它們的類型(如果有任何共同點) –

回答

3

你有一張地圖,從一些去(具有refcommits)。只需使用字符串索引器:

interface BranchByName { 
    [branchName: string]: { 
    ref: any; 
    commits: any; 
    } 
}