'Angular - Error when trying to overwrite sortingDataAccessor
I want to overwrite sortingDataAccessor to make sorting my table work with all of its columns. However, I keep running into error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Job'.
Here is how I am trying to overwrite the sortingDataAccessor:
this.dataSource.sortingDataAccessor = (item, property) => {
switch (property) {
case "date":
return item.jobDate;
default:
return item[property];
}
};
The error is being thrown here:
item[property]
What am I doing wrong and how can I properly overwrite this function without getting this error?
Solution 1:[1]
The problem is that the string type of the property parameter is a bit too broad for your needs. So this property can be any string whatsoever, but the keys that you can use to index the Job type is a limited collection of strings. You can instruct the compiler to think that the property will be a valid indexer for your item by telling it that:
return item[property as keyof Job];
You could also do something a bit more creative, like saving the current sortingDataAccessor in a variable before assigning your custom handler, and then using it for all the other properties for which you don't want to override the default behavior:
const originalSortingDataAccessor = this.dataSource.sortingDataAccessor;
this.dataSource.sortingDataAccessor = (item, property) => {
switch (property) {
case "date":
return item.jobDate as any;
default:
return originalSortingDataAccessor(item, property);
}
};
Solution 2:[2]
I cannot reproduce the error but it seems like the property has the type string and this type cannot be used to access a property of the Job class. However, I would need to see how this class looks in order to say more about this.
Generally, you can resolve the problem with some type-casting e.g. (item, property: any) => {...}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Simon |
