Home > Software design >  Angular Pipe -- Element implicitly has an 'any' type because expression of type 'stri
Angular Pipe -- Element implicitly has an 'any' type because expression of type 'stri

Time:03-03

Coming across the following error when creating this time ago pipe:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

if (value) {
      const seconds = Math.floor(
        ( new Date() -  new Date(Number(value))) / 1000
      );
      if (seconds < 60) {
        return "Just now";
      }
      const intervals = {
        year: 365 * 24 * 60 * 60,
        month: (52 * 7 * 24 * 60 * 60) / 12,
        week: 7 * 24 * 60 * 60,
        day: 24 * 60 * 60,
        hour: 60 * 60,
        minute: 60,
        second: 1
      };
      let counter;
      for (const i of Object.keys(intervals)) {
        counter = Math.floor(seconds / intervals[i]);
        if (counter > 0) {
          if (counter === 1) {
            return counter   " "   i   " ago"; // singular
          } else {
            return counter   " "   i   "s ago"; // plural
          }
        }
      }
    }
    return value;
intervals[i]

This portion is causing the error.

I've tried a few different ways of changing the type or accessing this object but I'm coming up short in the solution.

CodePudding user response:

Typescript gives you this error because you haven't declared that this object has keys of type string that return a number.

const intervals: { [key: string]: number } = {
...
}

Keys can be of type string, number, symbol, or template literal and you can specify that each returns a different type. If you do not specify, then the type checker can only assume the return type is any, and it will not be able to catch bugs in subsequent code.

Doc reference: https://www.typescriptlang.org/docs/handbook/2/objects.html#index-signatures

CodePudding user response:

I added:

"suppressImplicitAnyIndexErrors": true,

to tsconfig.json to fix this.

  • Related