I am using Vu3 typescript. I wanted to inject echarts into the component. but typescript keeps asking me what is a type of echarts that i injected. that is why I used any type as a solution. but I think It is not a good way. can u guys tell me what is type of echarts.
plugin file (where echarts was provided):
import * as echarts from "echarts";
import { App } from "vue";
export default {
install: (app: App) => {
app.provide("echarts", echarts);
},
};
component file:
<template>
<div ref="theChart" :style="{ height: '500px' }"></div>
</template>
<script lang="ts">
import { defineComponent, inject } from "vue";
export default defineComponent({
name: "login",
components: {},
setup() {
const echarts: any = inject("echarts");
return {
echarts,
};
},
mounted() {
this.drawChart();
},
methods: {
drawChart() {
//Initialize the echarts instance based on the prepared dom
let myChart = this.echarts.init(this.$refs.theChart, null, { renderer: 'svg' });
//Specify configuration items and data for the chart
let option = {
title: {
text: "ECharts Introductory example",
},
tooltip: {},
legend: {
data: ["Sales volume"],
},
xAxis: {
data: [
"shirt",
"Cardigan",
"Chiffon shirt",
"trousers",
"High-heeled shoes",
"Socks",
],
},
yAxis: {},
series: [
{
name: "Sales volume",
type: "bar",
data: [5, 20, 36, 10, 10, 20],
},
],
};
//Use the configuration items and data just specified to display the chart.
myChart.setOption(option, true);
},
},
});
</script>
when I write
const echarts = inject("echarts");
it shows error TS2571: Object is of type 'unknown' for the following code
let myChart = this.echarts.init(this.$refs.theChart, null, { renderer: 'svg' });
CodePudding user response:
there are two ways to resolve,You can choose a way that is convenient for you
1、if you are using npm, the default ts type of echarts is in a separate npm package, you can try to introduce it instead of any
npm install --save-dev @types/echarts
2、you can define a .d.ts file, define the types yourself
declare module "echarts" {
//the function or properties you may need to use
}
you use a provide,inject, but it doesn't make any sense, you can import echarts when you need
//@types/echarts does not need to import
import echarts from 'echarts'
app.provide('echarts',echarts);
//you use inject
const echarts = inject<typeof echarts>('echarts');