Home > OS >  Angular - Error when trying to overwrite sortingDataAccessor
Angular - Error when trying to overwrite sortingDataAccessor

Time:03-29

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?

CodePudding user response:

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];

CodePudding user response:

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

  • Related