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")。可以通过两种方式修复:- 使用
as const断言类型:const data = [ { x: [1, 2, 3], y: [100, 50, 300], type: "bar" as const, name: "Health", }, ]; - 显式定义数据类型:从
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
相关产品推荐
相关产品推荐

