TypeScript类型或标准化数据的接口

时间:2018-10-17 09:29:36

标签: typescript flowtype typescript-typings normalizr typescript-types

TLDR:如何为标准化数据创建接口?

我正在使用TypeScript构建一个React应用程序。我使用Normalizr来规范API调用中的数据。

以文档为例,提供如下API响应:

快速入门 考虑一个典型的博客文章。单个帖子的API响应可能如下所示:

{
  "id": "123",
  "author": {
    "id": "1",
    "name": "Paul"
  },
  "title": "My awesome blog post",
  "comments": [
    {
      "id": "324",
      "commenter": {
        "id": "2",
        "name": "Nicole"
      }
    }
  ]
}

可以对此进行标准化:

{
  result: "123",
  entities: {
    "articles": {
      "123": {
        id: "123",
        author: "1",
        title: "My awesome blog post",
        comments: [ "324" ]
      }
    },
    "users": {
      "1": { "id": "1", "name": "Paul" },
      "2": { "id": "2", "name": "Nicole" }
    },
    "comments": {
      "324": { id: "324", "commenter": "2" }
    }
  }
}

我想为使用Normalizr的函数创建接口。到目前为止,这是我尝试过的:

export interface House {
  uuid: string;
  address: string;
}

export interface Citizen {
  uuid: string;
  name: string;
}

export interface NormalizedData<T> {
  [uuid: string]: T;
}

export interface Entity<T> {
  [name: string]: NormalizedData<T>;
}

export interface NormalizerResult<T> {
  result: any;
  entities: Entity<T>;
}

由于我必须在此处给出通用类型T,因此该方法只能处理一个实体。问题在于实体键可以具有几个不同类型的实体,例如。众议院和公民(以及更多)。我将如何处理呢? Normalizr自己的类型只返回{ result: any, entities: any }

1 个答案:

答案 0 :(得分:1)

我想你想要这样的东西

export interface NormalizerResult<T extends House | Citizen> {
  result: any;
  entities: Entity<T>;
}

P.S。当您100%知道响应的结构时,Typescript会更有用;如果每次响应都不同,则Typescript的作用就较小。如果前者是正确的,那么您应该为每个响应输入类型,例如

export interface NormalizerResultForHousesAndCitizensRequest {
  result: any;
  entities: {
    houses: NormalizedData<House>,
    citizens: NormalizedData<Citizen>,
  };
}