TypeScript结合React使用ag-grid时onGridReady参数抛出类型不匹配错误
ag-grid onGridReady 配置的TypeScript构建报错
问题描述
基于TypeScript + React技术栈开发项目时,使用ag-grid组件配置onGridReady事件回调,触发生产构建类型校验失败。
实际编写的回调实现代码:
import { AgGridEvent, ICellRendererParams, ModuleRegistry } from "@ag-grid-community/core"; const onGridReady = (params: AgGridEvent): void => { setGridApi(params.api); params.api.sizeColumnsToFit(); };
执行生产构建时,TypeScript抛出的完整错误堆栈:
Type error: No overload matches this call. Overload 1 of 2, '(props: Readonly<AgGridReactProps>): AgGridReact', gave the following error. Type '(params: AgGridEvent) => void' is not assignable to type '(event: GridReadyEvent) => void'. Types of parameters 'params' and 'event' are incompatible. Type 'GridReadyEvent' is not assignable to type 'AgGridEvent'. Types of property 'api' are incompatible. Type 'import("/Users/subha/admin/admin_demo/node_modules/ag-grid-community/dist/lib/gridApi").GridApi' is not assignable to type 'import("/Users/subha/admin/admin_demo/node_modules/@ag-grid-community/core/dist/cjs/gridApi").GridApi'. Types have separate declarations of a private property 'immutableService'. Overload 2 of 2, '(props: AgGridReactProps, context?: any): AgGridReact', gave the following error. Type '(params: AgGridEvent) => void' is not assignable to type '(event: GridReadyEvent) => void'. 104 | suppressCellSelection={true} 105 | frameworkComponents={{ editRenderer }} > 106 | onGridReady={onGridReady} | ^ 107 | </AgGridReact> 108 | </div> 109 | </div> info - Creating an optimized production build .npm ERR! code ELIFECYCLE
核心原因
- 传入
onGridReady属性的回调函数参数类型,与AgGridReact组件Props定义要求的GridReadyEvent事件类型不兼容 - 冲突根源为项目依赖目录中同时存在两套独立的GridApi类型定义:一套来自旧版无作用域包
ag-grid-community,另一套来自官方作用域包@ag-grid-community/core,两套类型对私有属性immutableService做了独立声明,被TypeScript识别为完全不同的类型,最终触发类型不匹配错误
修复方案
- 统一依赖来源:排查项目依赖树,移除重复安装的无作用域
ag-grid-community包,所有ag-grid相关的类型、模块引用统一从@ag-grid-community/core导入,从根本上消除多份类型定义的冲突 - 对齐组件类型定义:修改
onGridReady回调的入参类型,不要手动指定宽泛的AgGridEvent类型,直接使用ag-grid-react组件库暴露的GridReadyEvent类型作为入参类型,确保回调参数与组件要求的事件类型完全对齐
内容的提问来源于stack exchange,提问作者Subha Jayabalan
相关产品推荐
相关产品推荐

