Angular集成Google Charts报错:Type 'string'无法分配给类型'ChartType'
解决TS2322: Type 'string' is not assignable to type 'ChartType'错误
这个错误的核心原因是angular-google-charts的<google-chart>组件的type属性要求传入**ChartType枚举类型**,但你的代码里chartData.type被TypeScript推断为普通的string类型,导致类型不兼容。
以下是两种可行的解决方法:
方法一:显式指定type为ChartType类型
import { Component } from '@angular/core'; // 导入ChartType类型 import { ChartType } from 'angular-google-charts'; @Component({ selector: 'app-stock-performance-chart', templateUrl: './stock-performance-chart.component.html', styleUrls: ['./stock-performance-chart.component.css'] }) export class StockPerformanceChartComponent { chartData = { // 通过类型断言将字符串转为ChartType type: 'BarChart' as ChartType, data: [ ["PHP Books", 500], [".Net Books", 800], ["Java Books", 400], ], chartColumns: ['Books', 'Sell'], width: 1000, height: 400 }; }
方法二:为chartData定义完整的类型接口(更规范)
import { Component } from '@angular/core'; import { ChartType } from 'angular-google-charts'; // 定义图表数据的强类型接口 interface ChartData { type: ChartType; data: Array<Array<string | number>>; chartColumns: string[]; width: number; height: number; } @Component({ selector: 'app-stock-performance-chart', templateUrl: './stock-performance-chart.component.html', styleUrls: ['./stock-performance-chart.component.css'] }) export class StockPerformanceChartComponent { // 指定chartData的类型为ChartData chartData: ChartData = { type: 'BarChart', data: [ ["PHP Books", 500], [".Net Books", 800], ["Java Books", 400], ], chartColumns: ['Books', 'Sell'], width: 1000, height: 400 }; }
两种方法都能让TypeScript正确识别chartData.type的类型,解决类型不匹配的错误。
内容的提问来源于stack exchange,提问作者shyam yadav
相关产品推荐
相关产品推荐

