79345947

Date: 2025-01-10 14:04:06
Score: 0.5
Natty:
Report link

I defer to @Mark Wiemer's comment about Typescript inferring unknown. I found that I could get it to return the correct types by using typeof obj[K][number] in the return type.

function mapToCreateObjects<K extends keyof U, T, U extends Record<K, T[]>>(
    obj: U,
    key: K,
): Record<K, { create: typeof obj[K][number] }[]> {
  return {
    [key]: obj[key].map((item) => ({ create: item })),
  } as Record<K, { create: typeof obj[K][number] }[]>;
}

The transformedFruits variable now has this type:

{ vegetables: { create: number }[], fruits: { create: string }[] }

I hope this is helpful!

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @Mark
  • Low reputation (0.5):
Posted by: Ben Larson