Here's some code to consider:
const obj = {
a: 1,
b: 2
}
let possibleKey: string = 'a'
if (possibleKey in obj) console.log(obj[possibleKey])
When possibleKey in obj
evaluates to true, shouldn't we expect possibleKey
to have the type keyof typeof obj
? Why doesn't TypeScript automatically narrow down the type of string
to that specific type? Instead, it throws the error message:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: number; b: number; }'.