Angular 15集成Google Charts应用构建时出现TS2322类型报错
Angular 15升级后Google Charts类型不匹配问题解决
问题描述
原Angular 12项目中使用Google Charts运行正常,升级到Angular 15后构建时出现类型错误,搭建基础测试项目复现该问题,错误提示如下:
Error: app.component.html:4:6 - error TS2322: Type 'string' is not assignable to type 'ChartType'.
4 [type]="chartData.type"
~~~~app.component.ts:5:16
5 templateUrl: './app.component.html',
~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component AppComponent.
环境信息
执行ng v输出的环境配置:
Angular CLI: 15.0.5 Node: 18.12.1 Package Manager: npm 9.3.0 OS: linux x64 Angular: 15.2.9 ... animations, common, compiler, compiler-cli, core, forms ... platform-browser, platform-browser-dynamic, router Package Version --------------------------------------------------------- @angular-devkit/architect 0.1502.8 @angular-devkit/build-angular 15.2.8 @angular-devkit/core 15.2.8 @angular-devkit/schematics 15.0.5 @angular/cli 15.0.5 @schematics/angular 15.0.5 rxjs 7.5.7 typescript 4.8.4
解决方法
1. 类型适配处理
Angular 15对类型检查更严格,ChartType是枚举类型,不能直接赋值字符串。可以通过两种方式处理:
- 模板内强制类型转换:修改模板代码,将字符串转为
ChartType类型:[type]="chartData.type as ChartType" - 组件类中预定义枚举值:在组件里直接使用
ChartType枚举,避免字符串类型:import { ChartType } from 'angular-google-charts'; chartData = { type: ChartType.BarChart // 根据实际图表类型替换,如LineChart、PieChart等 };
2. 升级兼容依赖包
确保angular-google-charts包版本与Angular 15兼容,执行命令安装适配版本:
npm install angular-google-charts@latest --save
3. 临时关闭严格类型检查(不推荐)
若需快速临时绕过错误,可修改tsconfig.json中的严格类型配置,但长期使用会降低代码质量:
{ "compilerOptions": { "strict": false, "strictPropertyInitialization": false } }
内容的提问来源于stack exchange,提问作者stoshb
相关产品推荐
相关产品推荐

