【问题标题】:Map JSON object to TypeScript object automatically (Angular 2)自动将 JSON 对象映射到 TypeScript 对象(Angular 2)
【发布时间】:2016-11-07 22:28:40
【问题描述】:

我是 Typescript 和 javascript 的新手。 我的问题是: 如何从这个

```

{
    "release": {
        "ref": {},
        "commits": {}
    },
    "debug": {
        "ref": {},
        "commits": {}
    },
    "feature": {
        "ref": {},
        "commits": {}
    },
    "hotfix": {
        "ref": {},
        "commits": {}
    }
}

```

使用接口将其与 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);
    }
}

```

【问题讨论】:

  • 属性的类型有哪些?如果您不需要它们的强类型,您可以使用 for-in 迭代对象的属性。如果您需要在编译时对它们中的每一个进行强类型化,您能否指定它们将具有的类型(如果有任何共同点)

标签: json dictionary typescript angular2-services


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-11-07
    • 2018-07-20
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 2012-02-06
    • 1970-01-01
    • 2017-12-24
    相关资源
    最近更新 更多