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!