You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React TypeScript集成Chart.js遇类型不兼容错误求助

解决React TypeScript集成Chart.js时的TS2322类型错误

问题描述

我是Chart.js新手,在尝试将Chart.js与React TypeScript集成时出现编译错误。错误信息如下:

TS2322:Type 'keyof ChartTypeRegistry' is not assignable to type '"bar"'. Type '"line"' is not assignable to type '"bar"'

报错位置在src/components/BarCharts.tsx第63行,我的组件代码如下:

import styled from '@emotion/styled';
import { ChartData } from 'chart.js';
import { Bar } from 'react-chartjs-2';
import { Country } from '../types';

interface Props {
  countries: Country[];
}

const options = {
  plugins: {
    legend: {
      display: false,
    },
  },
};

const ChartWrapper = styled.div`
  max-width: 700px;
  margin: 0 auto;
`;

const BarChart: React.FunctionComponent<Props> = ({ countries }) => {
  const generateChartData = (): ChartData => {
    const data: number[] = [];
    const labels: string[] = [];

    countries.forEach((country) => {
      data.push(country.NewConfirmed);
      labels.push(country.Country);
    });

    return {
      labels,
      datasets: [
        {
          label: 'New Confirmed',
          data,
          backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)',
          ],
          borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)',
          ],
          borderWidth: 1,
        },
      ],
    };
  };

  return (
    <ChartWrapper>
      <Bar type="bar" data={generateChartData()} options={options} />
    </ChartWrapper>
  );
};

export default BarChart;

错误原因

  1. 多余的type属性:react-chartjs-2中的Bar组件本身就是为柱状图设计的,它的类型定义里并不接收type这个props,手动传入type="bar"会触发类型不匹配错误。
  2. 泛型缺失:ChartData是泛型类型,未指定具体图表类型时,TypeScript无法推断出数据与柱状图的匹配关系,会引发潜在类型问题。

修复方案

修复后的代码

import styled from '@emotion/styled';
import { ChartData } from 'chart.js';
import { Bar } from 'react-chartjs-2';
import { Country } from '../types';

interface Props {
  countries: Country[];
}

const options = {
  plugins: {
    legend: {
      display: false,
    },
  },
};

const ChartWrapper = styled.div`
  max-width: 700px;
  margin: 0 auto;
`;

const BarChart: React.FunctionComponent<Props> = ({ countries }) => {
  // 明确指定ChartData的泛型为'bar'
  const generateChartData = (): ChartData<'bar'> => {
    const data: number[] = [];
    const labels: string[] = [];

    countries.forEach((country) => {
      data.push(country.NewConfirmed);
      labels.push(country.Country);
    });

    return {
      labels,
      datasets: [
        {
          label: 'New Confirmed',
          data,
          backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)',
          ],
          borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)',
          ],
          borderWidth: 1,
        },
      ],
    };
  };

  return (
    <ChartWrapper>
      {/* 移除多余的type="bar"属性 */}
      <Bar data={generateChartData()} options={options} />
    </ChartWrapper>
  );
};

export default BarChart;

关键修改点

  • 移除<Bar>组件上的type="bar"属性,Bar组件已内置柱状图类型定义。
  • 为ChartData添加泛型参数<'bar'>,明确数据对应柱状图类型,保证类型安全。

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 12:39:51