方案一:失败
在typescript+Vue的项目中引用echarts,为了加强引用,引入echarts和@types/echarts两个包,一个是工程依赖,一个是声明依赖。
npm install echarts --save
npm install --save @types/echarts
然后在需要引用echarts的组件中引入echarts
<script lang="ts"> …… import echarts from ‘echarts‘; …… </script>
然后设置好option选项,将图表渲染在DOM里:
// HTML部分 <div ref="chart"></div> // Script部分 option={}; const Chart = echarts.init(this.$refs.chart as HTMLCanvasElement); Chart.setOption(this.option);
按理来说是这样的,然后我run的时候图表显示也是正确的,但是控制台爆出了类型不兼容的错误,如下:
Argument of type ‘{ color: string[]; legend: { data: { name: string; textStyle: { color: string; fontSize: number; }; }[]; right: number; top: number; itemWidth: number; itemHeight: number; padding: number; itemGap: number; }; xAxis: { ...; }; yAxis: { ...; }; grid: { ...; }; series: { ...; }[]; }‘ is not assignable to parameter of type ‘EChartOption<SeriesBar | SeriesBoxplot | SeriesCandlestick | SeriesCustom | SeriesEffectScatter | SeriesFunnel | SeriesGauge | SeriesGraph | SeriesHeatmap | SeriesLine | SeriesLines | ... 10 more ... | SeriesTreemap>‘. Types of property ‘xAxis‘ are incompatible. Type ‘{ type: string; data: string[]; boundaryGap: boolean; axisLabel: { textStyle: { color: string; }; }; axisLine: { lineStyle: { type: string; color: string[]; width: string; }; }; }‘ is not assignable to type ‘XAxis | XAxis[] | undefined‘. Type ‘{ type: string; data: string[]; boundaryGap: boolean; axisLabel: { textStyle: { color: string; }; }; axisLine: { lineStyle: { type: string; color: string[]; width: string; }; }; }‘ is not assignable to type ‘XAxis‘. Types of property ‘type‘ are incompatible. Type ‘string‘ is not assignable to type ‘"value" | "category" | "time" | "log" | undefined‘. 124 | draw() { 125 | const Chart = echarts.init(this.$refs.chart as HTMLCanvasElement); > 126 | watchChart.setOption(this.option);
总之就是xAxis的问题,我看了一下 @types/echarts 中关于x轴参数的声明,对照官网的参数配置,实在是没找出为什么……
但是把option中xAxis删除了,只留下series、legend等,就不会出现上述错误……
方案二:成功但是不够严谨
最后删除了 @types/echarts ,在 echarts.d.ts 中自定义了 echarts 的声明 ,
declare module ‘echarts‘ { const echarts: any; export default echarts; }
然后引用成功并且没有爆出类型错误。
其实引用 @types/echarts 才是上上策,但是我花了三小时看文档和源码里面的声明,也没找出哪里定义的冲突了,就只好自己把 echarts 定义为了 any 类型。
希望以后有时间找下到底option的配置哪里有问题。
如果有大神知道为什么,麻烦给点指示 ??谢谢
原文:https://www.cnblogs.com/catherinezyr/p/10768399.html