【问题标题】:typescript declare map type打字稿声明地图类型
【发布时间】:2020-09-01 17:26:08
【问题描述】:

我正在使用 typescript,我需要 decare 一个类型来描述这种数据格式:

{
  "apple": [{"color": "red","taste": "good"}, {"color":"green", "taste": "bad"}],
  "banana":[{"color": "yellow","taste": "okay"}]
}

这就是我现在所拥有的,我声明了一个 Fruit 类型并使用 Record 将其制作为一个映射,然后我添加了字符串作为键(这将是水果名称,如苹果、香蕉)并声明了一个类型/接口 @ 987654322@ class 作为 Fruit 的值。

type Fruit = Record<string, FruitDescription>

interface FruitDescription {
  color: string,
  taste: string
}

通过这种设置,我无法推断出上述数据的类型。

谁能给我更好的建议来解决这类问题?谢谢你的帮助。

【问题讨论】:

  • 最难的问题是那些你试图找出错误但它不存在的问题。我认为这很好,只是你在 FruitDescription 之前缺少界面
  • > 但我感觉有些不对劲 是不是意味着它可以编译了?还是只是一种感觉?
  • FruitDescription 应该是一个接口或类型
  • 这是一张通用地图怎么样?

标签: javascript typescript


【解决方案1】:

您的类型注释中似乎缺少一组水果描述。

type Fruit = Record<string, FruitDescription[]>

【讨论】:

    【解决方案2】:

    除了 AdamExchange 已经提到的,如果您有如下定义的接口

    interface FruitDescription {
      color: string;
      taste: string;
    }
    

    您也可以尝试以下两个选项 -

    const m: { [name: string]: FruitDescription[] } = {
       "apple": [{"color": "red","taste": "good"}, {"color":"green", "taste": "bad"}],
       "banana":[{"color": "yellow","taste": "okay"}]
    };
    

    或者你可以使用ES6/TypescriptMap -

    let map : Map<string, FruitDescription[]> = new Map<string, FruitDescription[]>();
    
    map.set("apple", [{"color": "red","taste": "good"}, {"color":"green", "taste": "bad"}])
    map.set( "banana", [{"color": "yellow","taste": "okay"}])
    
    console.log(map.get("apple"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-16
      • 2022-01-06
      • 2017-08-12
      • 2021-01-20
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多