POV
POV

Reputation: 12005

How to specify type for Map javascript?

I have two Map():

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

After fill words I need to add this map into dictionaryMap.

So,how to specify type for dictionaryMap?

I tried:

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

But seems it is wrong.

Upvotes: 1

Views: 3706

Answers (2)

Ali Habibzadeh
Ali Habibzadeh

Reputation: 11548

You need to set the values or use ! to declare they can remain not initialised at the beginning.

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]])
  }
}

About your SubjectBehaviour wrapping. I lack some context as to what your needs are but if what you need is to subscribe to dictionary changes. then something like this should help:

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();

Upvotes: 1

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37594

You would need to initialize it first like this

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

and then put it inside the map with a key

dictionaryMap.set("yourKey", new Map<string, IDictItem>());

Upvotes: 1

Related Questions