Typescript 中对象的对象的接口结构

Neh*_*a M 0 javascript oop interface typescript typescript-generics

从服务器接收到的 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",
      }
    }
  },
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

export type Fruits = {
  fruitName: string
  type: object<FruitTypes>
}
Run Code Online (Sandbox Code Playgroud)

我不明白的是如何在 Fruits 中声明类型? type: object<FruitTypes>不管用。它将成为对象的对象。我们如何在 Typescript 中描述这一点。

Tho*_*mas 5

我更喜欢使用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;
}
Run Code Online (Sandbox Code Playgroud)

或者你可以明确地写出来

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

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

export type Product = {
  productCode: string;
  productName: string;
  color: string;
}
Run Code Online (Sandbox Code Playgroud)

Fruits整个构造的类型在哪里。