Home > Back-end >  Element implicitly has an 'any' type because expression of type 'string' can
Element implicitly has an 'any' type because expression of type 'string' can

Time:12-16

I have sortDynamic function where I'm trying to sort data dynamicaly like this:

 const sortDynamic = (key: string, order: string) => {
    const sortOrder = order === 'asc' ? 1 : -1;
    return (a: ProductMapData, b: ProductMapData) => {
       const A = typeof a[key] === 'string' ? a[key].toUpperCase() : a[key];
       const B = typeof b[key] === 'string' ? b[key].toUpperCase() : b[key];
       if (A < B) {
          return sortOrder * -1;
       } else if (A > B) {
          return sortOrder * 1;
       } else {
          return 0;
       }
    };
 };

and where ProductMapData is an interface looking like this:

interface ProductMapData {
  advanceRevenue: number;
  advanceTickets: number;
  changeInPeriodRevenue: number;
  changeInPeriodTickets: number;
  currency: string;
  entityRef: string;
  eopAdvanceRevenue: number;
  eopAdvanceTickets: number;
  hallLabel: string;
  occurredAt: string | undefined;
  playedOffRevenue: number;
  playedOffTickets: number;
  relatedEventName: string;
  thumbnail: string;
  timeBegins: string;
  timedBeginsBegins: string;
  soldTickets: number;
  soldRevenue: number;
}

and the function is called here:

productMapData.sort(sortDynamic('soldTickets', 'asc'));

Everything seems fine, but I'm getting this error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ProductMapData'. No index signature with a parameter of type 'string' was found on type 'ProductMapData'.ts(7053) on a[key] and b[key]. I don't know what am I doing wrong. Any help will be appreciated.

CodePudding user response:

Extend your ProductMapData interface to other interface that is strict with the typeof Key. The value can be any type of you can specify the type for value as well.

Below is the strict interface for ProductMapData for you. You can add more types for value.

interface IObjectKeys {
  [key: string]: string | number | undefined;
}

Now you just need to extend your ProductMapData interface to IObjectKeys.

interface ProductMapData extends IObjectKeys

This will tell your instance that your object have key of type string only.

Play the Playground Link

  • Related