Genady Mager Genady Mager - 3 years ago 192
TypeScript Question

working with complex types in interfaces in (typescript)

I'm pretty new to type script and java script.

My question is:
I have an interface, in which one of it's properties is Map .

I have a json object that is the same structure as the interface, when one of it's entries is another object. I'm trying to assign the json object to variable of the interface, but when i try to use the Map functions it says that it these functions do not exist.

it's probably because Map is not initialized.

for example, this is the json object:

let obj =
firstArg: "first"
secondArg: {one: 1, two: 2}

and this is the interface:

interface example {
firstArg: string,
secondArg: Map<string , number>


let exm: example = obj;

is not working.

what is the best solution to make this work?

Answer Source

An Object is not a Map. You will need to convert between Objects and Maps yourself:

function objectToMap<K extends string, V>(obj: Record<K,V>): Map<K, V> {
  // return new Map(Object.entries(obj)); 
  const map = new Map<K, V>();
  Object.keys(obj).forEach((k:K) => map.set(k, obj[k]));
  return map;

function mapToObject<K extends string, V>(map: Map<K, V>): Record<K, V> {
  const obj = {} as Record<K, V>;
  map.forEach((v, k) => { obj[k] = v; });
  return obj;

So you could do:

let obj =
    firstArg: "first",
    secondArg: objectToMap({ one: 1, two: 2 })

let exm: example = obj; // works now

Using something like objectToMap() and mapToObject(), you will need to write code that converts between the JSON you are getting/sending and your data model with Maps in it. Hope that helps; good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download