【问题标题】:How to declare the TypeScript Type for a Java Map of Map of Sets?如何为 Set Map of Sets 的 Java Map 声明 TypeScript 类型?
【发布时间】:2019-02-03 01:36:30
【问题描述】:

在 Java 中我有这样的东西:

public class MyMatrix implements Map<Long, Map<Long, Set<MyObject>>> {...}

我想做的是在TypeScript中声明这个Map的对应类型。

对应的JSON是:

{
   "1":{
      "1":[{"id":1},{"id":2}]
   },
   "2":{
      "1":[{"id":2},{"id":3}]
   }
}

我希望能够使用关联数组表示法来访问它,例如myArray[1][1] should return [{"id":1},{"id":2}]

我尝试过使用类似的东西

var myMatrix: Array<Array<Array<MyObjec>>>;

但没有运气。

尝试以下代码时:

for (const x in Object.keys(this.myMatrix)) {
  for (const y in Object.keys(this.myMatrix[x])) {
  }
}

我在第二个 for 循环中收到以下错误:

ERROR TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)

希望我发现了一点提示:这个错误的原因似乎是在第一个循环中Object.keys是从'0'而不是'1'开始的,这对我。

【问题讨论】:

  • 既然你使用的是 typescript,为什么不使用 ES6 MapSet 呢?像这样定义你的变量:let myMatrix: Map&lt;number, Map&lt;number, Set&lt;any&gt;&gt;&gt;;

标签: java arrays json typescript dictionary


【解决方案1】:

HugoTeixeira 的类型对我来说很合适。这段代码:

for (const x in Object.keys(this.myMatrix)) {
  for (const y in Object.keys(this.myMatrix[x])) {
  }
}

应该是:

for (const x of Object.keys(this.myMatrix)) {
//           ^^
  for (const y of Object.keys(this.myMatrix[x])) {
  }
}

【讨论】:

    【解决方案2】:

    您可以为每一层创建一种类型,如下所示:

    interface Column { 
        id: number;
    }
    
    interface Row { 
        [key: number]: Array<Column>;
    }
    
    class Matrix {
        [key: number]: Row;
    }
    

    然后你可以像这样创建一个矩阵:

    const myMatrix: Matrix = {  
        "1":{
            "1":[{"id":1},{"id":2}]
        },
        "2":{
            "1":[{"id":2},{"id":3}]
        }
    };
    

    从 Typescript 代码中,您可以根据需要使用关联数组表示法访问矩阵:

    const arr = myMatrix[1][1];
    console.log(JSON.stringify(arr));
    

    打印出来:

    [{"id":1},{"id":2}]
    

    【讨论】:

      【解决方案3】:

      我们可以在 Typescript 中声明 Maps,因此您可以尝试使用类似下面的内容,然后使用 foreach 对其进行迭代。

      var dataMap = new Map<number, Map<number,Array<Obj>>>();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-02
        • 2022-12-02
        • 2016-01-06
        • 1970-01-01
        • 2021-04-26
        • 2019-12-17
        • 1970-01-01
        • 2015-11-17
        相关资源
        最近更新 更多