Converting Object to Map using Generics Problem

I am loading things from the localStorage and this has to be saved as json, so it needs to have a simple Object structure to be possible to JSON.parse().

However, som methods do not accept &lt;any&gt; as parameter, because they want a concrete class or interface, but i want to send my object as parameter, so i have to convert it to a Map in order to have the same structure, but seen as it has a type, it is now accepted as parameter.

My problem lies within the conversion from Object to Map

Solution

public static convertObjectToMap&lt;V&gt;(obj: any, classOfV): Map&lt;string, V&gt; {
    let objectMap = new Map&lt;string, V&gt;();
    if (obj !== undefined &amp;&amp; obj !== null) {
      for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
          const initObject = new classOfV(obj[key]);
          objectMap.set(key, initObject);
        }
      }
    }
    return objectMap;
  }


I take an obj and the class which all values are going to be in the same type.

Example of usage

//This is purely for the example
const fibonacciObject:any = {"0": 1, "1": 1, "2": 2, "3": 3, "4": 5};

const fibonacciMap:Map&lt;string, Number&gt; = convertObjectToMap&lt;Number&gt;(fibonacciObject, Number);

fibonacciMap.get("0"); //1
fibonacciMap.get("4"); //5


Question

Is there a better way to do this conversion, i know about new () =&gt; V, but since i need it for each key, then it is not really feasible.

Also what Type would class of V be, i keep getting type errors when i try to give it a Type
A few points first.


Avoid any like the plague. You can nearly always figure out a better type. When dealing with a JSON serialized data, I like to have a function similar to this to get rid of any as soon as possible:

function verify&lt;T&gt;(obj: any, fallback: T, isT: (obj: any) =&gt; obj is T): T {
  return isT(obj) ? obj : fallback;
}

Object.keys and Object.entries are a better fit for looping through an object if you are going to check hasOwnProperty. I prefer Object.entries when possible, if you have the browser support.
Choose const or let, don't mix them without good reason. const can result in better type inference so I prefer to use it when possible.


Here is how I would implement this function.

function convertObjectToMap&lt;In, Out&gt;(
  obj: { [K: string]: In } | undefined | null,
  classOfIn: new (v: In) =&gt; Out
): Map&lt;string, Out&gt; {
  const result = new Map&lt;string, Out&gt;();

  for (const [key, val] of Object.entries(obj || {})) {
    result.set(key, new classOfIn(val));
  }

  return result;
}