You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

AmChart JS转TS遇类型错误:Object不存在seriesDataItem属性

Fixing Type Error with 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 legendData as LegendEntry[], TypeScript knows every item in the array has a seriesDataItem property.
  • Casting Data Context: Using as LegendEntry tells TypeScript that the dataContext conforms to our custom interface, eliminating the type error when accessing seriesDataItem.
  • Non-Null Assertion: The ! after dataItem.column.fill assumes that fill is always present. If there's a chance it could be null, replace it with optional chaining (dataItem.column?.fill) and handle the undefined case.

This approach keeps your code type-safe while maintaining the original functionality of toggling series items via the legend.

内容的提问来源于stack exchange,提问作者Praveen

火山引擎 最新活动