自动将JSON对象映射到TypeScript对象(Angular 2)

use*_*998 4 json dictionary typescript angular2-services

我是Typescript和javascript的新手.我的问题是:怎么做到这一点

```

{
    "release": {
        "ref": {},
        "commits": {}
    },
    "debug": {
        "ref": {},
        "commits": {}
    },
    "feature": {
        "ref": {},
        "commits": {}
    },
    "hotfix": {
        "ref": {},
        "commits": {}
    }
}
Run Code Online (Sandbox Code Playgroud)

```

使用接口使用Typescript映射它

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

```

bas*_*rat 6

你有一张地图,从一些已知 string的结构到已知结构的对象(有ref commits).只需使用字符串索引器:

interface BranchByName {
  [branchName: string]: {
    ref: any;
    commits: any;
  } 
}
Run Code Online (Sandbox Code Playgroud)