I'm trying to define a function typed with FlowJS using generics and I don't understand why it's raising an error in this function since I've got another one similar which works just fine.
For example, this is the one that is correct. Takes a map object and returns an array of objects.
const toArray = <T: { code: string }, U: { [code: string]: T }>(mapObject: U): T[] =>
Object.keys(mapObject).map((code: string): T => mapObject[code]);
Usage example
const ITEM1 = {code: "code1", otherObjProp: "otherProp"};
const ITEM2 = {code: "code2", otherObjProp: "otherProp"};
const object = { code1: ITEM1, code2: ITEM2 };
toArray(object); // [ITEM1, ITEM2]
Well, in the order hand I've this other function, supposed to do the inverse job. Received an array of objects and gets a map object.
In getting error message Cannot call array.reduce because object literal [1] is incompatible with U
const toMapObject = <T: { code: string }, U: { [code: string]: T }>(array: T[]): U =>
array.reduce(
(acc: U, item: T): U => ({
...acc,
[item.code]: item,
}),
{}
);
Usage example
const ITEM1 = { code: "code1", otherObjProp: "otherProp" };
const ITEM2 = { code: "code2", otherObjProp: "otherProp" };
const array = [ ITEM1, ITEM2 ];
toMapObject(array); // { code1: ITEM1, code2: ITEM2 }
Any idea why this could be happening? Thx!