I'm using a for loop to get strings from an array. I need to use these strings as object keys.
This code works when run but TypeScript complains:
const arr = ['one', 'two'];
const map = {
one: 'Vaue is 1',
two: 'Value is 2'
}
for (let i=0; i < arr.length; i++) {
const item = arr[i];
const res = map[item]
console.log(res)
}
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ one: string; two: string; }'.
No index signature with a parameter of type 'string' was found on type '{ one: string; two: string; }'.(7053)
itemis a valid key ofmap? As the error tells you, the type is inferred asstring, and there are plenty of strings that are neither'one'nor'two'. Can you givearraconstassertion?