0

I have the following function that goes through all the attributes of an object and converts them from ISO strings to Dates:

function findAndConvertDates<T>(objectWithStringDates: T): T {

    for (let key in Object.keys(objectWithStringDates)) {

        if (ISO_REGEX.test(objectWithStringDates[key])) {
            objectWithStringDates[key] = new Date(objectWithStringDates[key]);

        } else if (typeof objectWithStringDates[key] === 'object') {
            objectWithStringDates[key] = findAndConvertDates(
                objectWithStringDates[key]
            );
        }
    }
    return objectWithStringDates;
}

TypeScript keeps telling me that Element implicitly has an 'any' type because type '{}' has no index signature - referring to the numerous instances of objectWithStringDates[key].

Considering that the object is passed in as a generic object, how would I set about accessing these properties without an explicit index signature?

(otherwise how do I supply an index signature or suppress this error?)

Thanks!

MysteriousWaffle
  • 439
  • 1
  • 5
  • 16

1 Answers1

4

You can make an indexable signature like this:

function findAndConvertDates<T extends { [key: string]: any }>(objectWithStringDates: T): T {

Jesse Carter
  • 20,062
  • 7
  • 64
  • 101
  • I tried this `export interface IGApiResponse extends GaxiosResponse {}; let tmpData: IGApiResponse; ` But when trying to get one of the property of tmp data, I got error of type script : ` const test = tmpData.data["test"] ` error : `Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'unknown'`. If I add `any`, no errors, but not type safe...` const test =( tmpData.data as any)["test"]` – Jerome Jun 15 '19 at 07:51