声明具有显式类型node.js的字典



我正在使用node.js:

进行此操作
var cart = {}

在for循环中我做

cart[id] = []
cart[id].push(element)

当然,购物车中总会有一个元素。

我想做类似:

的事情
var cart: {'':[]} = {}

有一种巧妙的方式做到这一点吗?

 class Dictionary extends Map {
   constructor(){
     super();
   }
   add(id, data){
     if(this.has(id)){
       this.get(id).push(data);
     }else{
       this.set(id, [data]);
     }
     return this;
   }
}

所以可以做:

const dictionary = new Dictionary();
dictionary
  .add(1, "el")
  .add(2,"el")
  .add(1,"el2");
console.log(dictionary.get(1));

您可以初始化包含这样元素的数组:

cart[id] = [element];

最新更新