方案一:推薦
在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);
最后發現所有在@type/echarts(node_modules/@types/echarts/index.d.ts)里面聲明的一些聯合變量類型,類似於下圖所示的這種,都會出現這種問題:

也可以說是一個字符串字面量類型,詳見: https://ts.xcatliu.com/advanced/string-literal-types.html
我在引用處代碼里面option配置是:

因為聲明的時候type是個聯合類型,而不是type?:string這種類型,所以導致直接配置參數出現錯誤:

最后查看了網上的解決辦法:https://zhuanlan.zhihu.com/p/28902584
可以直接 const ec = echarts as any; 但是這種做法很不可取。
最后在 https://jkchao.github.io/typescript-book-chinese/typings/literals.html#%E6%8E%A8%E6%96%AD 找到了解決辦法,可以采用一個簡單的類型斷言來告訴 TypeScript 想推斷的字面量:
在本實例中就是:
option = { xAxis: { type: ('category' as 'category'), axisLine: { lineStyle: { type: ('dashed' as 'dashed'), }, }, }, }
到此,完美解決了我的問題(其實是個大神幫我找到的解決方法,在此感謝所有的前輩們)。
方案二:成功但是不夠嚴謹
最后刪除了 @types/echarts ,在 echarts.d.ts 中自定義了 echarts 的聲明 ,
declare module 'echarts' { const echarts: any; export default echarts; }
然后引用成功並且沒有爆出類型錯誤,但是失去了ts強引用的優勢。
方案三:簡單直接
![]()
直接越過ts的類型檢查………………………………………………
