React+TypeScript+Next.js使用ApexCharts时options属性报类型错误
错误原因
Type '{ ... }' is not assignable to type 'ApexOptions'. The types of 'chart.type' are incompatible between these types. Type 'string' is not assignable to type '"area" | "line" | "bar" | ... '
这个报错的核心是:TypeScript 默认会将对象内的字符串值自动推断为宽泛的string类型,而ApexCharts要求options.chart.type必须是指定的图表类型字面量联合类型,二者类型不匹配触发错误。
解决方法
下面按推荐优先级排序:
方法1:给options添加官方类型注解(最推荐)
直接导入ApexCharts官方提供的ApexOptions类型,给你的配置对象标注类型,从根源上保证类型合法:
import dynamic from 'next/dynamic'; import React from 'react'; // 新增导入官方类型 import type { ApexOptions } from 'apexcharts'; export const Chart: React.FC = () => { const ApexCharts = dynamic(() => import('react-apexcharts'), { ssr: false }); const barOptions = { width: '100%', series: [ { name: 'group1', data:[44, 55, 41, 64, 22, 43, 21], }, { name: 'group2', data: [53, 32, 33, 52, 13, 44, 100], }, ], // 给options标注ApexOptions类型 options: { colors: ['#008080 ', '#008000 '], chart: { type: 'bar', height: 430, }, plotOptions: { bar: { horizontal: true, dataLabels: { position: 'top', }, }, }, dataLabels: { enabled: true, offsetX: -6, style: { fontSize: '12px', colors: ['#fff'], }, }, stroke: { show: true, width: 1, colors: ['#fff'], }, tooltip: { shared: false, intersect: false, }, xaxis: { categories: ['1', '2', '3', '4', '5', '6', '7', '8'] }, } as ApexOptions, }; return ( <ApexCharts options={barOptions.options} series={barOptions.series} type="bar" /> ); }; // 注意:原代码末尾多了多余的右括号,已修正
方法2:用as const冻结配置类型
如果你不想额外导入类型,可以用as const告诉TypeScript不要拓宽对象内的字符串类型,保留字面量类型即可:
const barOptions = { // 所有配置内容不变 } as const;
方法3:传递时临时类型断言(仅临时消错用,不推荐)
如果只是想快速消除报错,可以在传递options时直接断言为ApexOptions类型:
<ApexCharts options={barOptions.options as ApexOptions} series={barOptions.series} type="bar" />
内容的提问来源于stack exchange,提问作者aaa
相关产品推荐
相关产品推荐

