I have created a function that generates an object (map) [key] : value from an array.
My goal is to make the value
method optional, and if not provided, simply return the item as it is.
Here is the code I have written:
export default class ArrayUtils {
/** Return a map from array like { [key]: value } */
static toMap = <T, T2 = void, V = T2 extends void ? T : T2>(
array: T[],
key: (item: T) => string | number,
value: (item: T) => V = (item: T) => item,
): { [key: string | number]: V } => Object.fromEntries(array.map((item) => [key(item), value(item)]));
}
However, I am encountering an error in my IDE:
Type '(item: T) => T' is not assignable to type '(item: T) => V'.
Type 'T' is not assignable to type 'V'. 'V' could be instantiated with an arbitrary type which could be unrelated to 'T'
I have attempted to overload the function without success. How can I achieve the desired functionality?