Currently, I am creating a declaration file for a library called chart.js. The process of constructing a new chart involves the following:
let chart = new Chart(ctx, { type: 'line', data: ..., options: ... })
The types of the data and options fields are determined by the type field.
To address this, my approach was to define the object's type as a union type. This allows me to specify the acceptable objects that can be passed into the constructor using string literal types for the type field.
However, after construction, the data and options fields become accessible properties from the class. Since I cannot utilize the types of the fields from the passed-in object, I am considering using generics instead.
The current issue is that I would need separate type parameters for each field (type, data, and options), but the specific types of data and options depend on the type specified in the type field. Not all combinations are valid. Is there a method to restrict the possible combinations of type parameters? For example:
let lineChart = new Chart<'line', LineChartData, LineChartOptions> // Valid
let barChart = new Chart<'bar', BarChartData, BarChartOptions> // Valid
let chart = new Chart<'line', BarChartData, LineChartOptions> // Invalid