Consider this code:
const obj = {
a: 1,
b: 2
}
let possibleKey: string = 'a'
if (possibleKey in obj) console.log(obj[possibleKey])
When possibleKey in obj
is true, we know that possibleKey
has type keyof typeof obj
, right? Why doesn't TypeScript type system detects that and narrows down string
to that type? Instead, it says:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: number; b: number; }'.
possibleKey in obj
is true, we know thatpossibleKey
has typekeyof typeof obj
, right?" not exactly.possibleKey
could be coming from the prototype ofobj
. Not sure if TS considers this an important distinction but it might, in which casepossibleKey
won't be a(n own) key ofobj
. – PrairialhasOwnProperty
check. – Dedans