【发布时间】:2019-02-13 16:39:34
【问题描述】:
我有以下函数,它遍历对象的所有属性并将它们从 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