typescript generic is an invalid type of proposal

Viewed 36

Should return an object with keys depending on the received array

const KEY_1 = '1';
const KEY_2 = '2';
const cache = {mget: (d: string[]) => Promise.resolve<{[d in string]: string}>({})}

async function getFromCache1<T extends typeof KEY_1 | typeof  KEY_2>(
  userId: number,
  keys: T[] = [KEY_1, KEY_2]
//             ~~~~~  ~~~~~
// Type '"1"' is not assignable to type 'T'.
//  '"1"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '"1" | "2"'.(2322)
): Promise<{[d in T]?: string}> {
  const ids = keys.map(e => [e, `${userId}:${e}`]);
  const caches = await cache.mget(ids.map(e => e[1]));
  return ids.reduce((acc, x) => ({ ...acc, [x[0]]: caches[x[1]] }), {});
}

https://tsplay.dev/w1pO8W

0 Answers
Related