0

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.

0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

I added:

"suppressImplicitAnyIndexErrors": true,

to tsconfig.json to fix this.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.