Encountering a TypeScript error with the code block below:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ id: string; path: string; basename: string; createdOn: string; modifiedOn: string; content: string; }'.
Square brackets function well in JavaScript (or using //@ts-ignore
).
What is the correct approach in TypeScript?
export interface Data {
[key: string]: {
id: string
path: string
basename: string
createdOn: string
modifiedOn: string
content: string
}
}
const data = _data as Data // _data represents JSON
for (let item in data) {
for (let property in data[item]) {
console.log(property)
if (["createdOn", "modifiedOn"].includes(property)) {
data[item][property] = new Date(data[item][property])
}
}
}
Shown below is the JSON structure of _data
.
{
"readme": {
"id": "3905d7917f2b3429490b01cfb60d8f5b",
"path": "README.md",
"basename": "README.md",
"createdOn": "2020-02-26T12:29:26.181Z",
"modifiedOn": "2020-02-26T12:29:26.181Z",
"content": "<!--\nTitle: Privacy guides\nDescription: Privacy guides will be published shortly...\n-->\n\n# Privacy guides\n\nPrivacy guides will be published shortly...\n"
},
...
}