Reputation: 405
const data = {
"a": "111",
"b": "222"
}
for (let key in data){
console.log(data[key]); // TypeScript error here
}
Error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ "a": string; "b": string; }'. No index signature with a parameter of type 'string' was found on type '{ "a": string; "b": string; }'.
Upvotes: 0
Views: 142
Reputation: 186994
You could:
console.log(data[key as keyof typeof data]);
Which is pretty ugly.
But it seems like you are treating data
as a dictionary with string keys, rather than having specific properties of specific types. In which type data
with a string
index to be able to index it with arbitrary strings.
let data: { [key: string]: string } = { a: '111', b: '222' }
Upvotes: 1
Reputation: 66103
You need to add an index signature to data
, i.e.:
const data: { [key: string]: string } = {
a: '111',
b: '222'
}
Upvotes: 1