0

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

Wing
  • 8,438
  • 4
  • 37
  • 46
  • Does this answer your question? https://stackoverflow.com/questions/56505560/how-to-fix-ts2322-could-be-instantiated-with-a-different-subtype-of-constraint From the first answer: _In typescript, a concrete instance is not allowed to be assigned to a type parameter._ – lepsch Sep 12 '22 at 17:53
  • So I can't add types to a function that takes a list of available words and returns an object from that list? – Vlad Sirenko Sep 12 '22 at 18:02
  • You might as well just use a type assertion and a generic default as shown [here](https://tsplay.dev/WvAlkm). See the answer to the [linked question]((https://stackoverflow.com/questions/64359115/default-parameters-with-generics-in-typescript) for more info. – jcalz Sep 12 '22 at 20:25

0 Answers0