You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue+Chart.js传递图表数据遇类型错误,求解决方案

解决Chart.js类型错误:正确传递Store中的图表数据

问题

开发带图表的应用时,尝试将Pinia Store中的数据通过props传递给Line图表的data属性,触发TypeScript类型错误,提示datasets属性在Record<string, any>类型中缺失,但ChartData<"line">类型要求该属性必须存在。

错误信息

Property 'datasets' is missing in type 'Record<string, any>' but required in type 'ChartData<"line", (number | Point | null)[], unknown>'.ts(2741)

index.d.ts(3790, 3): 'datasets' is declared here.

types.d.ts(12, 5): The expected type comes from property 'data' which is declared here on type '{ readonly data: ChartData<"line", (number | Point | null)[], unknown>;'

解决方案

1. 为Chart组件的Props指定精确类型

原Chart组件的props仅声明为Object,TypeScript无法识别其符合Chart.js的要求类型,需要引入Chart.js官方类型并明确定义:

修改Chart.vue的<script setup lang="ts">部分:

<script setup lang="ts">
import { Line } from 'vue-chartjs'
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  ChartData,
  ChartOptions
} from 'chart.js'

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend
)

// 定义精确的props类型
const props = defineProps<{
  chartData: ChartData<'line'>;
  chartOptions: ChartOptions<'line'>;
}>();
</script>

2. 确保chartData计算属性始终返回合法结构

当Store中的typingTestResults未加载(为undefined)时,原代码会导致labels和datasets[0].data为undefined,需要提供默认值避免类型错误:

修改User.vue中的chartData计算属性:

const chartData = computed(() => {
  const currentUser = user.value;
  const typingTestResults = currentUser?.typingTestResults || []; // 空数组作为默认值

  return {
    type: 'line' as const,
    labels: typingTestResults.map(result => result.created_at),
    datasets: [
      {
        label: 'WPM',
        data: typingTestResults.map(result => result.wpm),
        acc: typingTestResults.map(result => result.accuracy),
        time: typingTestResults.map(result => result.duration_seconds),
        backgroundColor: 'rgba(255, 174, 0, 0.2)',
        borderColor: 'rgb(255, 174, 0)',
        borderWidth: 3,
        pointRadius: 6,
        tension: 0.1,
      }
    ],
  };
});

3. 修正计算属性的小问题

原代码中currentUser = user.value的注释有误,user是computed ref,在<script setup>中访问其值必须使用.value,保留user.value即可。

修改后说明

  • 通过为Props指定ChartData<'line'>类型,TypeScript能准确校验传入的chartData结构是否符合要求
  • 给typingTestResults设置空数组默认值,确保即使数据未加载,datasets和labels也始终是数组类型,不会出现undefined
  • 明确类型定义后,编辑器会提供更准确的代码提示,减少后续错误

内容的提问来源于stack exchange,提问作者Giuliano Maradei

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 20:33:10