我有以下函数遍历对象的所有属性并将它们从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]
的众多实例。
考虑到对象作为通用对象传入,如何在没有显式索引签名的情况下设置访问这些属性?
(否则我如何提供索引签名或抑制此错误?)
谢谢!
你可以像这样制作一个可索引的签名:
function findAndConvertDates<T extends { [key: string]: any }>(objectWithStringDates: T): T {