There is a peculiar occurrence in TypeScript that I cannot comprehend.
The desired outcome is to have a function structured like this:
function getDbRowFromRow<T, Key extends keyof T, R extends Pick<T, Key>>(
dbRow: T[],
key: Key,
row: R)
{
const map = new Map<T[Key], T>(dbRows.map(r => [r[key], r]));
// an error pops up at the key in this line
map.get(row[key]);
}
This particular error message is displayed:
Argument of type 'R[Key]' is not assignable to parameter of type 'T[Key]'.
Type 'R' is not assignable to type 'T'.
'T' could be instantiated with an arbitrary type which could be unrelated to 'R'.
It puzzles me where something might be wrong, as it should be evident that if R extends Pick<T, Key>, then that aspect of the two generic objects must be identical.
Moreover, even attempting to as T[Key]
on the row results in the usual insistence to first cast to unknown
. It appears that the types are not perceived to be remotely interconnected.
Hence, what am I overlooking? Is there a method by which I could genuinely breach that type restriction, or is this simply a peculiar TypeScript idiosyncrasy?
If necessary, I will share the actual dilemma that needs resolving. Initially, I believed that a condensed example would provide better clarity.