DevExpress PivotGrid TypeScript TS2345类型错误:添加日期分组字段失败
解决PivotGrid日期分组的TypeScript类型错误(TS2345)
错误信息
let dateGroups: { area: string; dataField: string; dataType: string; groupInterval: string; }[] Argument of type '{ area: string; dataField: string; dataType: string; groupInterval: string; }' is not assignable to parameter of type 'PivotGridDataSourceField'. Types of property 'area' are incompatible. Type 'string' is not assignable to type '"column" | "data" | "filter" | "row" | undefined'.ts(2345)
问题代码
let dateRollupFields = this.pibotGridSource.fields(); const createdAtIndex = dateRollupFields.map(o => o.caption).indexOf("Created At"); let dateGroups = [{ area: 'column', dataField: 'created_at_date', dataType: 'date', groupInterval: 'month' }, { area: 'column', dataField: 'created_at_date', dataType: 'date', groupInterval: 'year' }] dateRollupFields.splice(createdAtIndex + 1, 0, dateGroups[0]);
解决方法
问题根源是TypeScript自动推断的dateGroups类型过于宽泛:area被推断为通用string,但PivotGridDataSourceField要求area必须是"column"|"data"|"filter"|"row"|undefined这些特定字面量类型。
方法1:显式指定数组类型
先从对应UI库导入PivotGridDataSourceField类型,再给dateGroups声明正确类型:
import { PivotGridDataSourceField } from 'your-ui-library-path'; // 替换为实际库路径 let dateGroups: PivotGridDataSourceField[] = [{ area: 'column', dataField: 'created_at_date', dataType: 'date', groupInterval: 'month' }, { area: 'column', dataField: 'created_at_date', dataType: 'date', groupInterval: 'year' }]
方法2:给单个对象加类型断言
如果不想全局声明数组类型,可给每个字段对象加上类型断言:
let dateGroups = [{ area: 'column', dataField: 'created_at_date', dataType: 'date', groupInterval: 'month' } as PivotGridDataSourceField, { area: 'column', dataField: 'created_at_date', dataType: 'date', groupInterval: 'year' } as PivotGridDataSourceField]
两种方法都能解决类型不兼容问题,推荐方法1,代码可读性更强,能提前规避类型错误。
内容的提问来源于stack exchange,提问作者Casey
相关产品推荐
相关产品推荐

