Typescript中对象对象的接口结构

Posted

技术标签:

【中文标题】Typescript中对象对象的接口结构【英文标题】:Interface structure in Typescript for object of objects 【发布时间】: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 它是对象的对象。我不确定它是否会起作用。 很多东西都是对象的对象。大多数对象都是这样。具有键值对的事物,其中一些具有作为对象的值。我不确定我是否理解这个问题。 【参考方案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 是整个构造的类型。

【讨论】:

这正是我想要的。谢谢

以上是关于Typescript中对象对象的接口结构的主要内容,如果未能解决你的问题,请参考以下文章

TypeScript-接口

TypeScript:将新对象添加到对象数组中

检查对象是不是在运行时使用 TypeScript 实现接口

TypeScript,面向对象,类、构造函数、继承、抽象类、接口和封装

将 json 数据更改为 Angular 2 中的 Typescript 接口对象

Typescript中的接口