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

React+TypeScript中Plotly提示'bar'类型无效问题求助

问题

在React+TypeScript项目中运行Plotly柱状图最简示例时出现TypeScript错误,提示'bar'不是有效选项,但相同代码在非TypeScript的React项目中能正常运行。

报错信息

TS2769: No overload matches this call.
  Overload 1 of 2, '(props: PlotParams | Readonly<PlotParams>): Plot', gave the following error.
    Type '{ x: number[]; y: number[]; type: string; name: string; }[]' is not assignable to type 'Data[]'.
      Type '{ x: number[]; y: number[]; type: string; name: string; }' is not assignable to type 'Data'.
        Type '{ x: number[]; y: number[]; type: string; name: string; }' is not assignable to type 'Partial<ViolinData>'.
          Types of property 'type' are incompatible.
            Type 'string' is not assignable to type '"violin"'.
  Overload 2 of 2, '(props: PlotParams, context: any): Plot', gave the following error.
    Type '{ x: number[]; y: number[]; type: string; name: string; }[]' is not assignable to type 'Data[]'.

代码片段

import React from "react";
import Plot from "react-plotly.js";

function App() {
  const data = [
    {
      x: [1, 2, 3],
      y: [100, 50, 300],
      type: "bar",
      name: "Health",
    },
  ];
  

  return (
    <div className="App">
      <Plot data={data} />
    </div>
  );
}

export default App;

解决方案

  • 精确指定type的类型:TypeScript会自动把"bar"推断为宽泛的string类型,但react-plotly.js的类型定义要求type必须是特定的图表类型字面量(比如"bar")。可以通过两种方式修复:
    1. 使用as const断言类型:
      const data = [
        {
          x: [1, 2, 3],
          y: [100, 50, 300],
          type: "bar" as const,
          name: "Health",
        },
      ];
      
    2. 显式定义数据类型:从plotly.js导入对应图表的类型,指定数组元素类型:
      import { BarData } from 'plotly.js';
      
      // ...
      
      const data: BarData[] = [
        {
          x: [1, 2, 3],
          y: [100, 50, 300],
          type: "bar",
          name: "Health",
        },
      ];
      
  • 检查类型依赖:如果上述方法无效,确认是否安装了@types/plotly.js(react-plotly.js的类型依赖),未安装则执行:
    npm install @types/plotly.js --save-dev
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 05:58:18