我想要覆盖sortingDataAccessor,使我的表排序与它的所有列一起工作。然而,我总是碰到error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Job'。下面是我试图覆盖sortingDataAccessor的方式
this.dataSource.sortingDataAccessor = (item, property) => {
switch (property) {
case "date":
return item.jobDate;
default:
return item[property];
}
};在这里引发错误:item[property]
我做错了什么,如何正确地覆盖这个函数而不得到这个错误?
发布于 2022-03-28 13:43:31
问题是,对于您的需要,string类型的property参数有点过于宽泛。因此,这个property可以是任何字符串,但是可以用于索引Job类型的键是一个有限的字符串集合。您可以指示编译器认为property将是item的有效索引器,方法是:
return item[property as keyof Job];您还可以做一些更有创造性的事情,比如在分配自定义处理程序之前将当前的sortingDataAccessor保存在变量中,然后将其用于不想覆盖默认行为的所有其他属性:
const originalSortingDataAccessor = this.dataSource.sortingDataAccessor;
this.dataSource.sortingDataAccessor = (item, property) => {
switch (property) {
case "date":
return item.jobDate as any;
default:
return originalSortingDataAccessor(item, property);
}
};https://stackoverflow.com/questions/71647138
复制相似问题