Search code examples
node.jstypescriptgenericstypescript-genericsindex-signature

How do I access the properties of a generic object by index in TypeScript?


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!


Solution

  • You can make an indexable signature like this:

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