I'm working on code that creates a timeline chart for data. I want the code to accept an array of series, each containing data and various getters used to position and render the data on the chart.
Below is a simplified example of the code. The actual implementation would involve multiple getters on DataSeries<T>
and rendering with React, but those details are not relevant to my current issue.
export interface DataSeries<T> {
data: T[];
asNumber: (d: T) => number;
}
export function DataSeriesAsNumbers<T>(series: DataSeries<T>[]) {
series.forEach((s) => {
s.data.forEach((d) => {
console.log(s.asNumber(d).toFixed(0));
});
});
}
My problem arises when using the function and trying to infer the parameter type for the getNumber
callbacks based on the data provided in the accompanying data
property.
DataSeriesAsNumbers([
{
data: [
{ val: 1, seq: 12346 },
{ val: 2, seq: 12347 },
],
asNumber: (d) => d.val,
},
{
data: [
{ amount: 6, type: 5 },
{ amount: 20, type: 4 },
],
asNumber: (d) => d.amount,
},
]);
So far, I haven't been able to achieve this automatically. I've tried manually specifying types or disregarding types altogether by using
DataSeriesAsNumbers<T = any>
.
The issue seems to stem from the series: DataSeries<T>[]
part, where mixing different objects in the data
properties requires all getters to adhere to the same union type. This results in assigning a union type to the d
parameter:
https://i.sstatic.net/zJfbX.png
I've explored using the infer
keyword without success, and have come across syntax like [...T]
online but haven't been able to implement it successfully.
Is there a way to automatically infer the parameter type for callbacks based on the associated data array?