如何在TypeScript中通过索引访问通用对象的属性?

问题描述 投票:0回答:1

我有以下函数遍历对象的所有属性并将它们从ISO字符串转换为日期:

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一直告诉我Element implicitly has an 'any' type because type '{}' has no index signature - 指的是objectWithStringDates[key]的众多实例。

考虑到对象作为通用对象传入,如何在没有显式索引签名的情况下设置访问这些属性?

(否则我如何提供索引签名或抑制此错误?)

谢谢!

node.js typescript generics typescript-generics index-signature
1个回答
3
投票

你可以像这样制作一个可索引的签名:

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

© www.soinside.com 2019 - 2024. All rights reserved.