I am encountering an issue with the code snippet below: (TS Playground link)
type TDeliveriesStatsDatum<TName = string> = {name: TName; value: number};
type TDeliveriesStatsData<TName = string> = TDeliveriesStatsDatum<TName>[];
interface IDeliveriesStats {
meta: {
delivery_count: number;
transport_count: number;
};
progress: TDeliveriesStatsData<"done" | "not_done" | "cancelled">;
disputes: TDeliveriesStatsData<"disputed" | "undisputed">;
loading_punctuality: TDeliveriesStatsData<"ontime" | "delayed" | "unknown">;
unloading_punctuality: TDeliveriesStatsData<"ontime" | "delayed" | "unknown">;
cmr_document: TDeliveriesStatsData<"done_with_cmr_document" | "done_without_cmr_document">;
non_cmr_document: TDeliveriesStatsData<
"done_with_non_cmr_document" | "done_without_non_cmr_document"
>;
loading_delay: TDeliveriesStatsData;
unloading_delay: TDeliveriesStatsData;
loading_duration: TDeliveriesStatsData;
unloading_duration: TDeliveriesStatsData;
}
type DeliveriesStatsKeys = "progress" | "disputes" | "cmr_document" | "non_cmr_document";
type TPieChartData<T extends DeliveriesStatsKeys> = {
augmentedData: {name: string, value: number, dataKey: string, fill: string}[]
} & {
[K in IDeliveriesStats[T][0]["name"]]: number;
};
export const formatPieChartData = <K extends DeliveriesStatsKeys>(
data: IDeliveriesStats[K]
): TPieChartData<K> => {
return data.reduce(
(acc: TPieChartData<K>, datum: IDeliveriesStats[K][0]) => {
acc[datum.name] = datum.value;
acc.augmentedData.push({
...datum,
dataKey: datum.name,
fill: "colorsAndLabelsByDataKey[datum.name].fill,"
});
return acc;
},
{augmentedData: []} as TPieChartData<K>
);
};
The error message from the compiler states:
This expression is not callable.
Each member of the union type '{ (callbackfn: (previousValue: TDeliveriesStatsDatum<"done" | "not_done" | "cancelled">,
currentValue: TDeliveriesStatsDatum<"done" | "not_done" | "cancelled"',
currentIndex: number, array: TDeliveriesStatsDatum<...>[]) => TDeliveriesStatsDatum<...&...',
has signatures, but none of those signatures are compatible with each other.
To resolve this issue, I need to properly type IDeliveriesStats
or TPieChartData
so that TypeScript understands that acc[datum.name]
is correctly typed. How can I achieve this?