Typescript generic typesafe function to convert object to map

Viewed 23

I need to convert the response from a HTTP request containing a map as an object. The map-object should be converted so I can use it in TS in a typesafe way.

Suppose for example I have the following definitions:

type Language = 'en' | 'fr' | 'de' | 'it';

interface A {
  foo: string;
  bar: number;
}

// the "map"-object from the HTTP response
const sampleResponseA: object = {
  en: { foo: 'foo', bar: 42 } as A,
  fr: { foo: 'foo', bar: 42 } as A,
  de: { foo: 'foo', bar: 42 } as A,
  it: { foo: 'foo', bar: 42 } as A,
};

Then I can convert it to a map as follows:

const mapA: Map<Language, A> = new Map<Language, A>(Object.entries(sampleResponseA) as [Language, A][]);

However, I have other responses containing other maps as objects. For example:

const sampleResponseB: object = {
  key1: { baq: true, bla: {} } as B,
  key2: { baq: false, bla: {} } as B,
  anotherKey: { baq: true, bla: {} } as B,
  yetAnotherKey: { baq: false, bla: {} } as B,
};

const mapB: Map<Language, B> = new Map<string, B>(Object.entries(sampleResponseA) as [string, B][]);

Converting each object individually seems to be a lot of duplication for what is always the same operation. I want a generic function that can handle any object and convert it to a map of any type.

Following the example on StackExchange I tried the following:

function obj2Map<K, V>(obj: { [K: string]: V }): Map<K, V> {
  return new Map(Object.entries(obj) as [K, V][]);
}

const mapB2 = obj2Map<string, B>(sampleResponseB);

However that does not work since I cannot cast the entries to [K,V]. Also the call to obj2Map does not work because sampleResponseB is not assignable to { [K: string]: V }.

How would an obj2Map function look like? Is it possible at all?

0 Answers
Related