我有以下函数,可以遍历对象的所有属性并将它们从 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 隐式具有“any”类型,因为类型“{}”没有索引签名
- 指的是 objectWithStringDates[key]
的众多实例。
考虑到该对象作为通用对象传入,我将如何设置在没有显式索引签名的情况下访问这些属性?
(否则我如何提供索引签名或抑制此错误?)
谢谢!
最佳答案
您可以像这样创建可索引签名:
function findAndConvertDates<T extends { [key: string]: any }>(objectWithStringDates: T): T {
关于node.js - 如何在 TypeScript 中通过索引访问通用对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52237562/