如何在不破解 index.esm.d.ts 檔案的情況下實作如下所述的資料集的自定義屬性資料結構?
我想在折線圖中實作類似于此處的自定義資料集資料結構。我在 Angular 中執行此操作并使用ng2-charts。
相關庫版本:
"@angular/core": "^14.2.0"
"@types/chart.js": "^2.9.37"
"chart.js": "^3.9.1"
"ng2-charts": "^4.0.1"
"typescript": "~4.7.2"
"tslib": "^2.3.0",
這是我要實作的資料集資料結構的簡化版本:
data: [
{id: '1', nested: {value: 500, extra: 'one'}},
{id: '2', nested: {value: 1500, extra: 'two'}},
],
不幸的是,我在實作這個時收到以下打字稿錯誤:
error TS2322: Type '{ id: string; nested: { value: number; extra: string; }; }' is not assignable to type 'number | ScatterDataPoint | BubbleDataPoint | null'.
如果我使用 CustomDataPoint 修改 index.esm.d.ts 檔案:
export interface CustomDataPoint {
id: string,
nested: {
value: number,
extra: string
}
}
export interface ChartTypeRegistry {
...
line: {
chartOptions: LineControllerChartOptions;
datasetOptions: LineControllerDatasetOptions & FillerControllerDatasetOptions;
defaultDataPoint: CustomDataPoint | ScatterDataPoint | number | null; //### modified
// defaultDataPoint: ScatterDataPoint | number | null; //### original
metaExtensions: {};
parsedDataType: CartesianParsedData;
scales: keyof CartesianScaleTypeRegistry;
};
...
}
我不再收到打字稿錯誤。耶!(;P)
如何在不破解 index.esm.d.ts 檔案的情況下實作上述資料集的自定義屬性資料結構?
這是一個最小的代碼集來重現這個......
折線圖.component.ts:
import { Component, OnInit } from '@angular/core';
import {ChartConfiguration, ChartType} from "chart.js";
@Component({
selector: 'app-chart-one',
templateUrl: './chart-one.component.html',
styleUrls: ['./chart-one.component.css']
})
export class ChartOneComponent implements OnInit {
public chartData: ChartConfiguration['data'] = {
datasets: []
};
public chartOptions: ChartConfiguration['options'];
public chartType: ChartType = 'line';
constructor() {}
ngOnInit(): void {
this.chartData.datasets = [
{
data: [
{id: '1', nested: {value: 500, extra: 'one'}}, //TS Error here
{id: '2', nested: {value: 1500, extra: 'two'}}, //TS Error here
],
label: 'set 1',
borderColor: '#3cba9f',
fill: false,
}
]
this.chartOptions = {
responsive: true,
parsing: {
xAxisKey: 'id',
yAxisKey: 'nested.value'
},
};
}
}
line-chart.component.html:
<div style="display: block">
<canvas baseChart
[data]="chartData"
[options]="chartOptions"
[type]="chartType">
</canvas>
</div>
uj5u.com熱心網友回復:
如此處檔案中所述,您可以傳遞自己的自定義資料型別:
import {ChartData} from 'chart.js';
const datasets: ChartData<'bar', {key: string, value: number} []> = {
datasets: [{
data: [{key: 'Sales', value: 20}, {key: 'Revenue', value: 10}],
parsing: {
xAxisKey: 'key',
yAxisKey: 'value'
}
}],
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/522001.html
