【问题标题】:Interface structure in Typescript for object of objectsTypescript中对象对象的接口结构
【发布时间】:2020-10-30 15:07:14
【问题描述】:

从服务器接收到的 JSON 的结构是这样的(我更改了细节):

{
  "apple": {
    "fruitName": "apple",
    "types": {
      "greenApple": {
        "productCode": "P1",
        "productName": "Green Apple",
        "color": "green",
      },
      "galaApple": {
        "productCode": "P2",
        "productName": "Gala Apple",
        "color": "light red",
      },
      "redDelicious": {
        "productCode": "P3",
        "productName": "Red delicious apple",
        "color": "bright red",
      }
    }
  },
  "orange": {
    "fruitName": "orange",
    "types": {
      "mandarin": {
        "productCode": "P5",
        "productName": "Mandarin Oranges",
        "color": "orange",
      },
      "bloodOrange": {
        "productCode": "P6",
        "productName": "Blood Orange",
        "color": "red",
      }
    }
  },
}

我正在为我的项目使用 Typescript 设计一个接口结构。

到目前为止,我想出了这个:

export type FruitTypes = {
  [key: string]: Product,
}

export type Product = {
  productCode: string
  productName: string
  color: string
}

export type Fruits = {
  fruitName: string
  type: object<FruitTypes>
}

我不明白的是如何在 Fruits 中声明类型? type: object&lt;FruitTypes&gt; 不工作。它将成为对象的对象。我们如何在 Typescript 中描述这一点。

【问题讨论】:

  • 不就是type: FruitTypes吗?
  • @Taplar 它是对象的对象。我不确定它是否会起作用。
  • 很多东西都是对象的对象。大多数对象都是这样。具有键值对的事物,其中一些具有作为对象的值。我不确定我是否理解这个问题。

标签: javascript typescript oop interface typescript-generics


【解决方案1】:

我更喜欢使用Record<K,T>

export type Fruits = Record<string, FruitTypes>;

export type FruitTypes = {
  fruitName: string;
  types: Record<string, Product>;
}

export type Product = {
  productCode: string;
  productName: string;
  color: string;
}

或者你可以直接写出来

export type Fruits = {
  [key:string]: FruitTypes;
}

export type FruitTypes = {
  fruitName: string;
  types: {
    [key:string]: Product;
  };
}

export type Product = {
  productCode: string;
  productName: string;
  color: string;
}

Fruits 是整个构造的类型。

【讨论】:

  • 这正是我想要的。谢谢
猜你喜欢
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
  • 2012-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-31
  • 2017-10-09
相关资源
最近更新 更多