AmChart JS转TS遇类型错误:Object不存在seriesDataItem属性
seriesDataItem in AmCharts TypeScript Conversion The error you're seeing happens because TypeScript doesn't know about the custom seriesDataItem property you've added to the legend's data context—by default, dataContext is typed as a generic Object, which doesn't include that property. Here's how to fix this with proper TypeScript typing:
Step 1: Define a Custom Interface for Legend Data
First, create an interface that describes the structure of the data you're passing to the legend. This tells TypeScript exactly what properties to expect:
import type { SeriesDataItem, Color } from "@amcharts/amcharts4"; interface LegendEntry { name: string; fill: Color; seriesDataItem: SeriesDataItem; }
(Note: If you haven't already, install AmCharts 4 type definitions with npm install @types/amcharts4 --save-dev)
Step 2: Update the Event Handler with Typed Data
Rewrite your code to use this interface, ensuring TypeScript recognizes the seriesDataItem property in the data context:
series2.events.on("dataitemsvalidated", () => { const legendData: LegendEntry[] = []; series2.dataItems.each((dataItem) => { legendData.push({ name: `${dataItem.categoryY}: ${dataItem.valueX}%`, fill: dataItem.column.fill!, // Non-null assertion: use only if you're sure fill exists seriesDataItem: dataItem }); }); chart.legend.data = legendData; chart.legend.itemContainers.template.events.on("toggled", (event) => { // Cast the dataContext to our custom interface const legendEntry = event.target.dataItem.dataContext as LegendEntry; const seriesDataItem = legendEntry.seriesDataItem; console.log(seriesDataItem); if (event.target.isActive) { seriesDataItem.hide(series2.interpolationDuration, 0, 0, ["valueX"]); } else { seriesDataItem.show(series2.interpolationDuration, 0, ["valueX"]); } }); });
Key Fixes Explained:
- Typed Legend Data: By declaring
legendDataasLegendEntry[], TypeScript knows every item in the array has aseriesDataItemproperty. - Casting Data Context: Using
as LegendEntrytells TypeScript that thedataContextconforms to our custom interface, eliminating the type error when accessingseriesDataItem. - Non-Null Assertion: The
!afterdataItem.column.fillassumes thatfillis always present. If there's a chance it could benull, replace it with optional chaining (dataItem.column?.fill) and handle theundefinedcase.
This approach keeps your code type-safe while maintaining the original functionality of toggling series items via the legend.
内容的提问来源于stack exchange,提问作者Praveen




