我有两个Map()

private dictionaryMap = new Map();
private words = new Map<string, IDictItem>();


填充words之后,我需要将此地图添加到dictionaryMap中。

那么,如何为dictionaryMap指定类型?

我试过了:

private dictionaryMap = new Map<string, Map<string, IDictItem>()>();


但是似乎是错误的。

最佳答案

您需要设置值或使用!声明它们可以在开始时不进行初始化。

interface IDictItem {
  definition: string;
}

class Foo {
  private words = new Map<string, IDictItem>();
  private dictionaryMap: Map<string, Map<string, IDictItem>>;

  constructor(){
    this.words.set("hello", { definition: "word for greeting" });
    this.dictionaryMap = new Map([["key", this.words]])
  }
}


关于您的SubjectBehaviour包装。对于您的需求,我缺乏一些了解,但是如果您需要订阅词典更改的话。那么这样的事情应该有所帮助:

interface IDictItem {
  definition: string;
}

class Foo {
  private words = new Map<string, IDictItem>([["hello", { definition: "word for greeting" }]]);
  private dictionaryMap: Map<string, Map<string, IDictItem>>;
  // I was using jsfiddle, so you need to do an actual:
  // import { BehaviorSubject } from "rxjs";
  private dictionaryMapSubject = new rxjs.BehaviorSubject();
  private dictionaryKey = "key"


  constructor(){
    this.dictionaryMap = new Map([[this.dictionaryKey, this.words]]);
    this.dictionaryMapSubject.subscribe(console.log);
  }

  public publishDic(): void {
      const dic = this.dictionaryMap.get(this.dictionaryKey);
      this.dictionaryMapSubject.next(dic);
  }
}

const foo = new Foo();

foo.publishDic();

关于javascript - 如何为Map javascript指定类型?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56075292/

10-11 11:32