I am facing an issue with the following code snippet, where I am trying to restrict the pairing of Chart
objects based on correct types for the data
and options
objects. However, despite my efforts, the TypeScript compiler is not throwing an error in the specific scenario I want to prevent.
class Chart<TData extends ChartData<TOptions>, TOptions extends ChartOptions> {
public data?: TData;
public options?: TOptions;
}
interface ChartData<TOptions extends ChartOptions> { }
interface ChartOptions { }
interface BarChartData extends ChartData<BarChartOptions> { barChartData: number }
interface BarChartOptions extends ChartOptions { barChartOption: string }
interface PieChartData extends ChartData<PieChartOptions> { pieChartData: number }
interface PieChartOptions extends ChartOptions { pieChartOption: string}
const barChart = new Chart<BarChartData, BarChartOptions>();
const pieChart = new Chart<PieChartData, PieChartOptions>();
const mixedChart = new Chart<BarChartData, PieChartOptions>(); // expected compilation error
// Here is the case I want to avoid:
mixedChart.data = { barChartData: 7 } as BarChartData;
mixedChart.options = {pieChartOption: 'hello' } as PieChartOptions
// The mixing of BarChartData and PieChartOptions should be prevented
I need the ability to update options and data separately due to implementation requirements, which is why ChartData
does not have a property for options. Adding options: TOptions
to ChartData
would trigger the error, suggesting that not using TOptions
in ChartData
is causing the constraint to be ignored. How can I maintain this constraint without adding an unwanted/exposed property?