typescript - 错误:'类型 'keyof ChartTypeRegistry' 不能赋值给类型 '"bar"'。类型 '"line"' 不能赋值给类型 '"bar"'。'
我正在尝试将 Chart.js 与 React TypeScript 集成。我是 chart.js 的初学者,在进行项目时,我遇到了以下错误。
已编译,但存在问题:X
src/components/BarCharts.tsx 第63行第24列 错误
TS2322: 类型 'ChartData
' 不能赋值给类型 'ChartData<"bar", (number | ScatterDataPoint | BubbleDataPoint | null)[], unknown>'。类型 'keyof ChartTypeRegistry' 不能赋值给类型 '"bar"'。类型 '"line"' 不能赋值给类型 '"bar"'。 61 | return ( 62 | 63 | | ^^^^64 | 65 | ); 66 | };
所以这是 BarCharts.tsx 组件。
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
你需要将“bar”作为类型参数传递给 ChartData 类型,如下所示 ChartData<"bar">。