尝试编写一个使用 Chart.js 的 Stencil/React Web 组件时,我在为ChartConfiguration.options
. 专门为scales
属性应用正确的类型是有问题的。
现在看起来像这样:
private chartConfig: ChartConfiguration = {
type: 'scatter',
data: {
datasets: [],
},
options: {},
};
private scaleOptions = {
years: {
type: 'time',
adapters: {
date: {
locale: enUS,
},
},
time: {
unit: 'year',
tooltipFormat: 'yyyy',
},
bounds: 'data',
position: 'bottom',
} as ScaleOptionsByType<'time'>,
score: {
type: 'linear',
bounds: 'ticks',
min: 0,
max: 10,
position: 'left',
} as ScaleOptionsByType<'linear'>,
};
// Use it ...
private setChartScaleOptions() {
this.chartConfig.options.scales = this.scaleOptions;
}
private drawChart() {
new Chart(this.canvas, this.chartConfig);
}
以这种方式与操作员一起使用ScaleOptionsByType
界面as
感觉很脏。我更喜欢使用直接类型分别定义每个比例选项,如下所示:
private yearsScaleOptions: ScaleOptionsByType<'time'> = {
type: 'time',
adapters: {
date: {
locale: enUS,
},
},
time: {
unit: 'year',
tooltipFormat: 'yyyy',
},
bounds: 'data',
position: 'bottom',
}
private scoreScale: ScaleOptionsByType<'linear'> = {
type: 'linear',
bounds: 'ticks',
min: 0,
max: 10,
position: 'left',
}
// Use it ...
private setChartScaleOptions() {
this.chartConfig.options.scales = {
years: this.yearsScaleOptions,
score: this.scoreScaleOptions,
};
}
但这会抛出 (2/2) Type '{ type: "linear"; ...} is not assignable to {...} is missing the following properties from type 'CartesianScaleOptions': axis, offset, grid, title, and 19 more.
。
感觉这些扩展类型是不可用的,因为它们在编译时需要太多的属性,而这些属性不需要具有可运行的代码。我错过了什么?