-1

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?

Chris
  • 1,417
  • 4
  • 21
  • 53

2 Answers2

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);
  }
};
Octavian Mărculescu
  • 4,312
  • 1
  • 16
  • 29
  • Thanks for the clarification! Unfortunately, when I try this I now get the following error: Type '(item: Job, property: string) => string | number | boolean | Date | TranslatedString' is not assignable to type '(data: Job, sortHeaderId: string) => string | number'. This error is now thrown here: `this.dataSource.sortingDataAccessor`. Do I now have to somehow exclude the attributes which I already handle separately from the `keyof Job`, or what is going on here? – Chris Mar 29 '22 at 08:51
  • 1
    @Chris They seem to leave them as `any` in [the default sorting data accessor implementation](https://github.com/angular/components/blob/23f392995c791f3585cf816d9249d6f83143f52c/src/material/table/table-data-source.ts#L154). You should be fine by placing `as any` on the return values. – Octavian Mărculescu Mar 29 '22 at 09:51
  • 1
    I edited my answer to include a solution for your issue. – Octavian Mărculescu Mar 29 '22 at 10:02
0

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) => {...}

Simon
  • 194
  • 13