Структура интерфейса в Typescript для объекта объектов - PullRequest
0 голосов
/ 10 июля 2020

Структура 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<FruitTypes> не работает. Это будет объект объектов. Как это описать в машинописном тексте.

1 Ответ

2 голосов
/ 10 июля 2020

Я предпочитаю использовать Запись

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 - это тип всей конструкции.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...